《第一行代码(第2版)》5.3.1和5.3.2在模拟器上和真机上运行有些问题,这里我讲一下我的解决办法
我们知道注册广播的方式一般有两种:
1.在代码中注册(也被称为动态注册)。
2.AndroidManifest.xml中注册(也被称为静态注册)。
在同一个进程上发送自定义广播并接收:
首先建一个BroadcastTest空项目
第一步:使用Android Studio提供的快捷方式来创建一个广播接收器来准备接收此广播,点击app—>New—>Other—>Broadcast Receiver,这里将广播接收器命名为MyBroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"received in MyBroadcastReceiver",Toast.LENGTH_SHORT).show();
}
}
当MyBroadcastReceiver收到自定义广播时会弹出“received in MyBroadcastReceiver”的提示
第二步:在AndroidManifest.xml中对这个广播接收器进行修改
<manifest ...>
<application ...>
<receiver