Android判断网络状态
2016-05-12 09:29
393 查看
package com.ch.services; import com.ch.utils.NetWorkUtils; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; //这是后台 Service public class CopyOfOffLineService extends Service{ @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub //new一个新类 判断网络 NetWorkUtils netUtils = new NetWorkUtils(getApplicationContext()); int i = netUtils.netWorkType();//获得当前网络状态类型 //1.wifi 2.移动网路 3.没网 if(i == 1){ //请求数据,并保存 Log.i("TAG", "开始离线下载......"); }else if(i == 2){ Log.i("TAG", "提示是移动数据,是否继续下载......"); }else{ Log.i("TAG", "没网,不需要下载......"); } return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } }
package com.ch.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; import android.util.Log; public class NetWorkUtils { Context mcontext; public NetWorkUtils(Context mcontext){ this.mcontext = mcontext; } public int netWorkType(){ //获取管理 ConnectivityManager mConnectivity = (ConnectivityManager)mcontext.getSystemService(Context.CONNECTIVITY_SERVICE); TelephonyManager mTelephony = (TelephonyManager)mcontext.getSystemService(Context.TELEPHONY_SERVICE); //检查网络连接 NetworkInfo info = mConnectivity.getActiveNetworkInfo(); if (info == null || !mConnectivity.getBackgroundDataSetting()) { Log.i("TAG","网络未连接....."); return 3; } int netType = info.getType(); int netSubtype = info.getSubtype(); Log.i("TAG",netType+",,"+netSubtype+",,"+mTelephony.isNetworkRoaming()); if (netType == ConnectivityManager.TYPE_WIFI) { //WIFI Log.i("TAG","wifi连接....."); return 1; } else if (netType == ConnectivityManager.TYPE_MOBILE && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS && !mTelephony.isNetworkRoaming()) { //MOBILE Log.i("TAG","移动数据连接....."); return 2; } return 3; } }
相关文章推荐
- 没想到!网络美女直播背后的真相居然是这样
- HttpClient——Get,Post
- HttpURLConnection——get,post
- HttpEntity转换Inputstream(红色)加XmlPull解析
- 证书透明度Certificate Transparency
- 证书透明度Certificate Transparency
- 通过NSURLProtocol拦截HTTP转HTTPS来整合SPDY的记录
- .Net MVC Redirect出现:服务器无法在已发送 HTTP 标头之后设置状态解决方案
- HTTP协议详解
- 谈谈MVVM和链式网络请求架构
- App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Te
- TCP/IP
- Servlet和HTTPServlet的区别
- Deep Learning学习 之 卷积神经网络(CNN)
- Javase网络通讯(socket编程)群聊系统
- AESwithJCE http://www.coderanch.com/how-to/content/AES_v1.html
- TCP四步挥手的各种状态转换图
- bp神经网络及matlab实现
- Laxcus大数据管理系统2.0(8)- 第六章 网络通信
- 云计算:创业的好时机——上海够快网络科技有限公司总经理蒋烁淼专访(评价阿里云的OSS的4个优点)(够快科技正式宣布已成功挂牌新三板)