android监听网络状态,实时更新网络状态

手机在网络方面的的监听也比较重要,有时候我们必须实时监控这个程序的实时网络状态,android在网络断开与连接的时候都会发出广播,我们通过接收系统的广播就可以实现网络的监听

//监听器
    private NetState receiver=new NetState();
    private IntentFilter filter=new IntentFilter();

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

  

一个广播接收类-

private class NetState extends BroadcastReceiver{

  @Override
  public void onReceive(Context arg0, Intent arg1) {
   ConnectivityManager manager = (ConnectivityManager)con.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(con);
   
      //设定标题
        ab.setMessage("网络连接断开,请检查网络");
        //设定退出按钮
  
     //网络设置按钮
        ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
      
      @Override
      public void onClick(DialogInterface dialog, int which) {
       // TODO Auto-generated method stub
       dialog.dismiss();
       ShakeActivity.this.finish();
      }
     }).show();           
          
     }

}
  

 }

你可能感兴趣的:(android监听网络状态,实时更新网络状态)