标签:des android style blog class c
一、判断网络类型是wifi,还是3G,还是2G网络
ConnectivityManager connectMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
二、监控网络状态
以下代码可以监控网络是否连接,可以根据网络连接来做相应的操作;
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 }
Android判断网络类型以及监控网络状态,布布扣,bubuko.com
标签:des android style blog class c
原文地址:http://www.cnblogs.com/all88/p/3738695.html