本地广播和全局广播(按照传播范围)
本地广播(app内部传播)数据,其它app收不到,保证了数据的安全性
全局广播,可以在整个手机所有App之间传播通信,会有安全性问题。普通广播默认就是全局广播。
例如监听开机充电打电话发短信修改时间这些
1.本地广播只能通过动态注册
2.本地广播需要用LoaalBroadcasrManager
代码示例:
xml文件:
java代码:
本地广播类:MyLocalBroadcastReceiver
public class MyLocalBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "MyLocalBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: 收到了本地广播");
}
}
Activity类:LocalBroadCastActivity
public class LocalBroadCastActivity extends AppCompatActivity {
private MyLocalBroadcastReceiver myLocalBroadcastReceiver = new MyLocalBroadcastReceiver();
LocalBroadcastManager mLocalBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_local_broad_cast);
/**
* 本地广播只能动态注册
*/
//实例化
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
//注册广播接收器
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("local_broad_cast");
mLocalBroadcastManager.registerReceiver(myLocalBroadcastReceiver, intentFilter);
}
//发送本地广播
public void sendLocalBroadcast(View view) {
Intent intent = new Intent();
intent.setAction("local_broad_cast");
mLocalBroadcastManager.sendBroadcast(intent);
}
//解除注册
@Override
protected void onDestroy() {
super.onDestroy();
mLocalBroadcastManager.unregisterReceiver(myLocalBroadcastReceiver);
}
}