BroadcastReceiver动态注册案例
砖厂打工仔 人气:0BroadcastReceiver动态注册案例演示,供大家参考,具体内容如下
此案例共介绍2种动态注册广播接收器,为自定义广播接收器和系统广播接收器。当点击发送按钮后,将会弹出收到自定义广播的提示;当打开或关闭飞行模式时,会出现飞行模式发生变化的提示。
效果图:
代码:
MainActivity.java
public class MainActivity extends AppCompatActivity { private MyBroadcastReceiver receiver1; private NetReceiver receiver2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //1.动态注册自定义广播接收器 receiver1 = new MyBroadcastReceiver(); IntentFilter filter1 = new IntentFilter(); //使用包名作为自定义广播action filter1.addAction("com.example.a01dynamicregister"); registerReceiver(receiver1, filter1); //2.动态注册系统广播接收器 receiver2 = new NetReceiver(); IntentFilter filter2 = new IntentFilter(); //添加切换飞行模式action filter2.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);//当飞行模式打开或关闭时,接收该广播 registerReceiver(receiver2, filter2); //3.点击按钮发送自定义广播 findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent("com.example.a01dynamicregister");//注意:自定义广播的发送和接受内容必须一直,否则接收不到 sendBroadcast(intent); } }); } @Override protected void onDestroy() { super.onDestroy(); //记得用完需要销毁广播接收器 if (receiver1 != null) { unregisterReceiver(receiver1); } if (receiver2 != null) { unregisterReceiver(receiver2); } } } //接收自定义广播 class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Toast.makeText(context, "收到自定义广播了~~action为:" + action, Toast.LENGTH_LONG).show(); } } //接收系统广播 class NetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { Toast.makeText(context, "飞行模式发生变化~~", Toast.LENGTH_LONG).show(); } } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发送自定义广播"/> </LinearLayout>
加载全部内容