为网友们分享了相关的编程文章,网友姜琳淼根据主题投稿了本篇教程内容,涉及到BroadcastReceiver、动态注册、BroadcastReceiver动态注册案例相关内容,已被679网友关注,涉猎到的知识点内容可以在下方电子书获得。
BroadcastReceiver动态注册案例
BroadcastReceiver动态注册案例演示,供大家参考,具体内容如下
此案例共介绍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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持码农之家。