赞
踩
项目完整代码
https://github.com/Phil-tom/Android-The-First-Line-of-Code/tree/main/Chapter5
全局广播很容易引起安全性问题,为了能够简单地解决广播的安全性问题,Android引入了一套本地广播机制,使用这个机制发出的广播只能在应用程序内部传递,并且广播接收器也只能接收来自本应用程序发出的广播。
本地广播的用法并不复杂,主要使用了一个LocalBroadcastManager来对广播进行管理,并提供了发送广播和注册广播接收器的方法。
在build.gradle中添加
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
MainActivity.java
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private IntentFilter intentFilter; private LocalReceiver localReceiver; private LocalBroadcastManager localBroadcastManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); localBroadcastManager = LocalBroadcastManager.getInstance(this); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick: "); Intent intent = new Intent("com.zzz.mybroadcastreceiver.LOCAL_BROADCAST"); localBroadcastManager.sendBroadcast(intent); } }); intentFilter = new IntentFilter(); intentFilter.addAction("com.zzz.mybroadcastreceiver.LOCAL_BROADCAST"); localReceiver = new LocalReceiver(); localBroadcastManager.registerReceiver(localReceiver,intentFilter);//注册本地广播监听器 } @Override protected void onDestroy() { super.onDestroy(); localBroadcastManager.unregisterReceiver(localReceiver); } class LocalReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"received local broadcast",Toast.LENGTH_SHORT).show(); } } }
运行设备:Nexus 5X API 28
运行结果:
另外,本地广播是无法通过静态注册的方式接收的。静态注册主要是为了让程序在未启动的情况下也能收到广播,而发送本地广播时,程序肯定已经启动了,因此也完全不需要使用静态注册功能。
本地广播的优势:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。