我是靠谱客的博主 曾经小伙,这篇文章主要介绍Broadcast--本地广播,现在分享给大家,希望可以做个参考。

本地广播

  • android中本地广播机制,只允许广播在本程序中发送和接收,这样当在广播中包含信息时,也不会有信息的泄露的危险。
  • 本地广播的用法:使用一个LocalBroadcastManager来对广播进行管理,并提供了广播的发送和接收的方法。
  • 首先自定义广播接收器
复制代码
1
2
3
4
5
6
public class MyLocalReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "这是一条本地广播", Toast.LENGTH_SHORT).show(); } }
  • 然后使用LocalBroadcastManager在代码中对广播接收器进行注册和取消注册。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button button; private MyLocalReceiver myLocalReceiver; private LocalBroadcastManager localBroadcastManager; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button= (Button) findViewById(R.id.button_local); button.setOnClickListener(this); //获取实例 localBroadcastManager=LocalBroadcastManager.getInstance(this); myLocalReceiver=new MyLocalReceiver(); //设置intentFilter的值 IntentFilter intentFilter=new IntentFilter("com.lingzhuo.LOCAL_BROADCAST"); localBroadcastManager.registerReceiver(myLocalReceiver,intentFilter); } @Override protected void onDestroy() { super.onDestroy(); localBroadcastManager.unregisterReceiver(myLocalReceiver); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button_local: Intent intent=new Intent(); intent.setAction("com.lingzhuo.LOCAL_BROADCAST"); localBroadcastManager.sendBroadcast(intent); break; } } }
  • 效果图如下:
    这里写图片描述

最后

以上就是曾经小伙最近收集整理的关于Broadcast--本地广播的全部内容,更多相关Broadcast--本地广播内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(78)

评论列表共有 0 条评论

立即
投稿
返回
顶部