当前位置:   article > 正文

android 网络状态监听_android网络状态监听

android网络状态监听

主页面:

public class MainActivity extends Activity {
public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
MyReceiver mr = new MyReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerDateTransReceiver();

if(Utils.getActiveNetwork(MainActivity.this)==null){
Toast.makeText(this, "没有网络!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "网络良好!", Toast.LENGTH_LONG).show();
}


}


private void registerDateTransReceiver() {
Log.i("TAG", "register receiver " + CONNECTIVITY_CHANGE_ACTION);
IntentFilter filter = new IntentFilter();
filter.addAction(CONNECTIVITY_CHANGE_ACTION);
filter.setPriority(1000);
registerReceiver(mr, filter);
}
  
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
unregisterReceiver(mr);
finish();


}
}

工具类:

public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
MyReceiver mr = new MyReceiver();
public static NetworkInfo getActiveNetwork(Context context){
       if (context == null)
           return null;
       ConnectivityManager mConnMgr = (ConnectivityManager) context
               .getSystemService(Context.CONNECTIVITY_SERVICE);
       if (mConnMgr == null)
           return null;
       NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // 获取活动网络连接信息
       return aActiveInfo;
   }
MyRecevier:

public class MyReceiver extends BroadcastReceiver {
public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
 @Override
   public void onReceive(Context context, Intent intent) {
       String action = intent.getAction();
       Log.i("TAG", "PfDataTransReceiver receive action " + action);
       if(TextUtils.equals(action, CONNECTIVITY_CHANGE_ACTION)){//网络变化的时候会发送通知
           Log.i("TAG", "网络变化了");
           return;
       }
 }
}

最后在mainfaintext,xml文件中添加权限:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

添加广播:

        <receiver android:name="MyReceiver">
            <intent-filter >
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/576754
推荐阅读
相关标签
  

闽ICP备14008679号