Android learning-Dynamic Registration listening for network changes and android listening
Create a BroadcastTest project and modify the code in MainActivity as follows:
1 public class MainActivity extends AppCompatActivity {2 private IntentFilter intentFilter; 3 private NetworkChangeReceiver networkChangeReceiver; 4 5 @ Override 6 protected void onCreate (Bundle savedInstanceState) {7 super. onCreate (savedInstanceState); 8 setContentView (R. layout. activity_main); 9 intentFilter = new IntentFilter (); 10 intentFilter. addAction ("android.net. conn. CONNECTIVITY_CHANGE "); // wide Add the corresponding action11 networkChangeReceiver = new NetworkChangeReceiver (); 12 registerReceiver (networkChangeReceiver, intentFilter); // call resigerReceiver () method to register 13} 14 15 @ Override16 protected void onDestroy () {17 super. onDestroy (); 18 unregisterReceiver (networkChangeReceiver); 19} 20 21 class NetworkChangeReceiver extends BroadcastReceiver {22 @ Override23 public void onReceive (Context context, In Tent intent) {24 // Toast. makeText (context, "network changes", Toast. LENGTH_SHORT ). show (); 25 ConnectivityManager connectionManager = (ConnectivityManager) getSystemService (Context. CONNECTIVITY_SERVICE); // obtain the system service 26 NetworkInfo networkInfo = connectionManager. getActiveNetworkInfo (); 27 if (networkInfo! = Null & networkInfo. isAvailable () {28 Toast. makeText (context, "network is available", Toast. LENGTH_SHORT ). show (); 29} else {30 Toast. makeText (context, "network is unavailable", Toast. LENGTH_SHORT ). show (); 31} 32} 33} 34}
The dynamic register broadcast receiver must cancel registration. In the onDestroy () method, it is implemented by calling the unregisterReceiver () method.
To access the network status of the system, you need to declare the permission, open the AndroidManifest. xml file, and add the permission in it, as shown below:
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.administrator.broadcasttest"> 4 5 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 6 <application 7 android:allowBackup="true" 8 android:icon="@mipmap/ic_launcher" 9 android:label="@string/app_name"10 android:supportsRtl="true"11 android:theme="@style/AppTheme">12 <activity android:name=".MainActivity">13 <intent-filter>14 <action android:name="android.intent.action.MAIN" />15 16 <category android:name="android.intent.category.LAUNCHER" />17 </intent-filter>18 </activity>19 </application>20 21 </manifest>
Run the program, open the data connection, and close the data connection. The effect is as follows: