Android网络应用程序开发中,经常要判断网络连接是否可用,因此经常有必要监听网络状态的变化。
Android的网络状态监听可以用BroadcastReceiver来接收网络状态改变的广播,具体实现如下:
public class ConnectionChangeReceiver extends BroadcastReceiver {
private static final String TAG=ConnectionChangeReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "网络状态改变");
boolean success=false;
//获得网络连接服务
ConnectivityManager connManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// State state=connManager.getActiveNetworkInfo().getState();
// 获取WIFI网络连接状态
State state=connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// 判断是否正在使用WIFI网络
if (State.CONNECTED== state) {
success=true;
}
// 获取GPRS网络连接状态
state=connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// 判断是否正在使用GPRS网络
if (State.CONNECTED != state) {
success=true;
}
if (!success) {
Toast.makeText(context, context.getString(R.string.your_network_has_disconnected), Toast.LENGTH_LONG).show();
}
}
使用方式一:
1. 在Activity的onCreate中:
//注册网络监听
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver, filter);
2. 在Activity中的onDestroy中:
//取消监听
unregisterReceiver(mNetworkStateReceiver);
使用方式二:
1. 应用启动时,启动Service,在Service的onCreate方法中注册网络监听:
//注册网络监听
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver, filter);
2. 应用退出时,Service关闭,在Service的onDestroy方法中取消监听:
//取消监听
unregisterReceiver(mNetworkStateReceiver);