package com.mycompany.broadcasttest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; /** * 动态注册监听网路变化 */ 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); /** * 1、首先创建了一个IntentFilter实例,并给它添加了一个值为android.net.conn.CONNECTIVITY_CHANGE的action * 2、当网络发生变化时,系统发出的就是"android.net.conn.CONNECTIVITY_CHANGE"的广播 * 3、即我们的广播接收器里面想要监听什么广播,就在这里添加相应的action * 4、接着创建一个NetworkChangeReceiver的实例,然后调用registerReceiver方法进行注册,将networkChangeReceiver、networkChangeReceiver都传入 * 5、这样NetworkChangeReceiver就会收到值为"android.net.conn.CONNECTIVITY_CHANGE"的广播 * 6、重要:动态注册的广播接收器一定要取消注册才行,调用unregisterReceiver()方法进行取消 */ intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); networkChangeReceiver = new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(networkChangeReceiver); } /** * 自定义了一个继承于BroadcastReceiver的内部类,并重写OnReceive()方法 * 这样每当网络状态发生变化是,OnReceive()都会得到执行 */ class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "network change", Toast.LENGTH_SHORT).show(); } } }
Android---动态注册监听网路变化的广播
最新推荐文章于 2021-10-22 14:05:39 发布