网上资料也很多,测试的时候大部分都不可运行,差点意思,所以这里自己整理了一份。
首先,自定义广播 发送端
<!-- 自定义的兄弟广播权限(只有符合这个权限的广播才可以接收处理) -->
<uses-permission android:name="com.brother.RECEIVE" />
<permission android:name="com.brother.RECEIVE" android:protectionLevel="normal"> </permission>
Intent intent = new Intent();
intent.setAction("action.kkkkkkkkk");
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); //设置为前台广播
sendBroadcast(intent,"com.brother.RECEIVE");
然后,接收端
<!-- 自定义的兄弟广播权限(只有符合这个权限的广播才可以接收处理) -->
<uses-permission android:name="com.brother.RECEIVE"/>
<permission android:name="com.brother.RECEIVE" android:protectionLevel="normal"> </permission>
<!--这里的第二个权限没测试是否可以去掉-->
<!-- 自定义广播接收器 (permission="com.brother.RECEIVE")-->
<receiver
android:name="com.test.KKReceiver"
android:exported="true"
android:label="@string/app_name"
android:permission="com.brother.RECEIVE">
<intent-filter>
<action android:name="action.kkkkkkkkk" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
public class KKReceiver extends BroadcastReceiver{
private String TAG = KKReceiver.class.getSimpleName();
@Override
public void onReceive(Context ctx, Intent intent) {
if(intent.getAction().equals("action.kkkkkkkkk")){
Log.e("进入报告广播", "此时的测试状态是:");
String name = intent.getStringExtra("name");
...
}
}
这就是所有代码了,不多就不传demo了。之前写过一篇类似的但是自己回头测试的时候有点逻辑问题,现在补一篇。