1、定义一个类,假设为StateBroadcastReceiver继承BroadcastReceiver,然后重写onReceive方法:
@Override
public voidonReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
State wifiState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();//获取wifi网络状态
State mobileState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();//获取移动数据网络状态
//没有执行return,则说明当前无网络连接
if(wifiState != State.CONNECTED&& mobileState != State.CONNECTED) {
System.out.println("------------> Network is validate");
intent.setClass(context, NetWorkErrorActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
return;
}
//判断网络是否已经连接
System.out.println("------------> Network is ok");
}
2、在Manifest文件中注册广播
<receiver android:name=".StateBroadcastReceiver" >
<intent-filter>
android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
3、别忘了加权限
网友评论