Android 监控网络状态
Android网络应用程序开发中,经常要判断网络连接是否可用,因此经常有必要监听网络状态的变化。android的网络状态监听可以用BroadcastReceiver来接收网络状态改变的广播,具体实现如下:
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "网络状态改变");
boolean success = false;
//获得网络连接服务
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
// State state = connManager.getActiveNetworkInfo().getState();
State state = connManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState(); // 获取网络连接状态
if (State.CONNECTED == state) { // 判断是否正在使用WIFI网络
success = true;
}
state = connManager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).getState(); // 获取网络连接状态
if (State.CONNECTED != state) { // 判断是否正在使用GPRS网络
success = true;
}
if (!success) {
Toast.makeText(LocationMapActivity.this, "您的网络连接已中断", Toast.LENGTH_LONG).show();
}
}
在Activity的onCreate中:
//注册网络监听
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver, filter);
//在Activity中的onDestroy中:'
unregisterReceiver(mNetworkStateReceiver); //取消监听
作者 crane
补充:移动开发 , Android ,