1.作用:
自定义的权限广播,权限代码可以自定义,要跟自定义权限代码一样,才可以接收到。类似密码,要有这个密码的app才能接收到这个广播。四大组件都是可以自定义权限的。
2.关键代码:
1.广播发送app
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent mIntent=new Intent();
mIntent.setAction("com.itheima.action.mybroadcast");//广播action标记
String receiverPermission="com.example.sunweihao";//权限标记(类似密码,有密码才能使用)
/**
* 参数1:表示intent,
* 参数2:表示接收者应该要具备这个权限,才能接收到这个广播
*/
sendBroadcast(mIntent,receiverPermission);
}
}
2.广播接收app
/**
* @ClassName MyBroadcastReceiver
* @Description TODO
* @Author ${孙伟豪}
* @Date 2020/10/29 11:51
* @Version 1.0
*/
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: "+intent);
Toast.makeText(context, "接收到广播", Toast.LENGTH_SHORT).show();
}
}
3.权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kunminx.mybroadcastreceiver">
<!--声明权限-->
<permission android:name="com.example.sunweihao"/>
<!--使用权限-->
<uses-permission android:name="com.example.sunweihao"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.itheima.action.mybroadcast"/>
</intent-filter>
</receiver>
</application>
</manifest>
3.步骤:
1.APP1 发送广播:
Intent mIntent=new Intent();
mIntent.setAction("com.itheima.action.mybroadcast");//广播action标记
String receiverPermission="com.example.sunweihao";//权限标记(类似密码,有密码才能使用)
/**
* 参数1:表示intent,
* 参数2:表示接收者应该要具备这个权限,才能接收到这个广播
*/
sendBroadcast(mIntent,receiverPermission);
2.APP2 接收广播:
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: "+intent);
Toast.makeText(context, "接收到广播", Toast.LENGTH_SHORT).show();
}
}
3.APP2 接收广播设置权限与声明广播:
声明权限与使用
<!--声明权限-->
<permission android:name="com.example.sunweihao"/>
<!--使用权限-->
<uses-permission android:name="com.example.sunweihao"/>
声明广播:
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.itheima.action.mybroadcast"/>
</intent-filter>
</receiver>
图解:
4.总结与反思:
1.问题
两个app都要运行