Android 动态注册监听网络变化实例详解
Android 动态注册监听网络变化实例详解
新建一个BroadcastTest项目,然后修改MainActivity中的代码,如下:
public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentFilter=new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); //广播接收器想要监听什么广播,就在这里添加相应的action networkChangeReceiver=new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver,intentFilter); //调用resigerReceiver()方法进行注册 } @Override protected void onDestroy(){ super.onDestroy(); unregisterReceiver(networkChangeReceiver); } class NetworkChangeReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ // Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show(); ConnectivityManager connectionManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); //得到系统服务类 NetworkInfo networkInfo=connectionManager.getActiveNetworkInfo(); if(networkInfo!=null&&networkInfo.isAvailable()){ Toast.makeText(context,"network is available",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context,"network is unavailable",Toast.LENGTH_SHORT).show(); } } } }
动态注册的广播接收器一定要取消注册才行,在onDestroy()方法中通过调用unregisterReceiver()方法来实现。
访问系统的网络状态需要声明权限,打开AndroidManifest.xml文件,在里面加入权限,如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.administrator.broadcasttest"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
运行程序,打开数据连接、关闭数据连接,效果如下:
以上就是Android 动态注册监听网路变化的实例详解,如果大家有疑问可以留言或者到本站社区交流,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
赞 (0)