第一步:自己定义权限,并且使用自定义权限
<uses-permission android:name="com.cn.customview.permissions.MY_BROADCAST" />
<permission
android:name="com.cn.customview.permissions.MY_BROADCAST"
android:protectionLevel="signature" >
</permission>
给这个应用程序定义了一个permissions并且uses-permission申明使用,这是这个应用就有了这个权限,并且应用内部的注册的动态广播也拥有了这个权限。
第二步:定义注册广播
private static final String BROADCAST_PERMISSION_DISC = “com.cn.customview.permissions.MY_BROADCAST”;
private static final String BROADCAST_ACTION_DISC = “com.cn.customview.permissions.my_broadcast”;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.broadcast_permissions_activity);
ButterKnife.bind(this);
// 注册广播接收
BroadcastReceiver receiveBroadCast = new ReceiveBroadCast();
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_ACTION_DISC); // 只有持有相同的action的接受者才能接收此广播
registerReceiver(receiveBroadCast, filter,BROADCAST_PERMISSION_DISC,null);
}
public class ReceiveBroadCast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(BroadcastPermissionsActivity.this,
"receive broadcast", 0).show();
}
}
注册一个广播,并且申明,这个广播需要BROADCAST_PERMISSION_DISC权限才能收到消息。但是我们应用程序已经注册了这个权限。所以是有这个权限的。
第三步: 发送广播
@OnClick(R.id.btn_send_broadcast)
public void sendBroadcastWithPermissions() {
Intent intent = new Intent(); //Itent就是我们要发送的内容
intent.putExtra("data", "this is data from broadcast "+Calendar.getInstance().get(Calendar.SECOND));
intent.setAction(BROADCAST_ACTION_DISC); //设置你这个广播的action,只有和这个action一样的接受者才能接受者才能接收广播
sendBroadcast(intent,BROADCAST_PERMISSION_DISC); //发送广播
}
转载:https://blog.csdn.net/u011733020/article/details/100123995
查看评论