Android判断网络类型以及监控网络状态
一、判断网络类型是wifi,还是3G,还是2G网络
ConnectivityManager connectMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectMgr.getActiveNetworkInfo();
一、判断网络是否是wifi,在判断之前一定要进行的非空判断,如果没有任何网络
连接info ==null
info.getType() == ConnectivityManager.TYPE_WIFI
二、判断是否是手机网络
info !=null && info.getType() == ConnectivityManager.TYPE_MOBILE
手机网络进行详细区分:
info.getSubtype() 这里使用 getSubtype(),不是 getType(),getType()返回的是0,或者1,是区分是手机网络还是wifi
info.getSubtype()取值列表如下:
* NETWORK_TYPE_CDMA 网络类型为CDMA
* NETWORK_TYPE_EDGE 网络类型为EDGE
* NETWORK_TYPE_EVDO_0 网络类型为EVDO0
* NETWORK_TYPE_EVDO_A 网络类型为EVDOA
* NETWORK_TYPE_GPRS 网络类型为GPRS
* NETWORK_TYPE_HSDPA 网络类型为HSDPA
* NETWORK_TYPE_HSPA 网络类型为HSPA
* NETWORK_TYPE_HSUPA 网络类型为HSUPA
* NETWORK_TYPE_UMTS 网络类型为UMTS
二、监控网络状态
以下代码可以监控网络是否连接,可以根据网络连接来做相应的操作;
1 import com.qdsj.hxcmjj.activity.MainActivity; 2 3 import android.app.Service; 4 import android.content.BroadcastReceiver; 5 import android.content.Context; 6 import android.content.Intent; 7 import android.content.IntentFilter; 8 import android.net.ConnectivityManager; 9 import android.net.NetworkInfo; 10 import android.os.IBinder; 11 12 public class NetMonitorService extends Service { 13 14 15 16 private ConnectivityManager connectivityManager; 17 private NetworkInfo info; 18 19 private BroadcastReceiver mReceiver = new BroadcastReceiver() { 20 21 @Override 22 public void onReceive(Context context, Intent intent) { 23 String action = intent.getAction(); 24 if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { 25 System.out.println("网络状态已经改变"); 26 connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 27 info = connectivityManager.getActiveNetworkInfo(); 28 if(info != null && info.isAvailable()) { 29 System.out.println("网络连接"); 30 context.startActivity(new Intent(context,MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); 31 } else { 32 System.out.println("网络断开"); 33 } 34 } 35 } 36 }; 37 38 39 @Override 40 public IBinder onBind(Intent intent) { 41 return null; 42 } 43 44 @Override 45 public void onCreate() { 46 super.onCreate(); 47 IntentFilter mFilter = new IntentFilter(); 48 mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 49 registerReceiver(mReceiver, mFilter); 50 System.out.println("开启网络监听服务"); 51 } 52 53 54 55 @Override 56 public void onDestroy() { 57 super.onDestroy(); 58 unregisterReceiver(mReceiver); 59 } 60 61 @Override 62 public int onStartCommand(Intent intent, int flags, int startId) { 63 return super.onStartCommand(intent, flags, startId); 64 } 65 66 67 68 69 }
文章来自:http://www.cnblogs.com/all88/p/3738695.html