android 实时检测网络状态

时间:2020-11-29 15:20:24

xml添加权限:

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

onCreate:注册帧听
NetState receiver = new NetState();
IntentFilter filter = new IntentFilter();

filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(receiver, filter);
receiver.onReceive(this, null);

添加类:

class NetState extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent arg1) {
ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(!gprs.isConnected() && !wifi.isConnected())
{
AlertDialog.Builder ab = new AlertDialog.Builder(context);
ab.setMessage("网络连接断开,请检查网络");
ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}).show();

}
else{
AlertDialog.Builder ab = new AlertDialog.Builder(context);
ab.setMessage("网络连接成功");
ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}).show();

}
}
}