安卓:动态注册广播
思路:创建一个类继承BroadcastReceiver类,在里面重写onReceive()方法,把接收到广播后需要添加的逻辑写在方法内public class MainActivity extends AppCompatActivity private Broad broad; private IntentFilter intentfilter;
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentfilter=new IntentFilter(); intentfilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); broad=new Broad(); registerReceiver(broad,intentfilter); } class Broad extends BroadcastReceiver{ public void onReceive(Context context,Intent intent){ ConnectivityManager connectionManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkinfo=connectionManager.getActiveNetworkInfo(); if(networkinfo!=null&&networkinfo.isAvailable()){ Toast.makeText(context,"network is avaliable",Toast.LENGTH_SHORT).show(); } else
Toast.makeText(context, "network is unavaliable", Toast.LENGTH_SHORT).show(); } } }
注意:1.有些访问时需要权限的,所以要在AndroidManifest.xml中添加权限。
2.动态注册的广播接收器一定要取消注册。