在有序广播中添加自定义权限

时间:2022-05-06 06:33:17

首先我们要在AndroidManifest.xml中自定义一个权限,格式参考系统自带的权限,android.permission.XXXXX,只要是xxx.peimission.XXXXXX就行,如果不按照这个格式,那么这个权限可能没法使用。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lsj.broadcasttest">
<span style="color:#FF0000;"> <permission
android:name="test.permission.TEST"
android:protectionLevel="normal"
></permission></span>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
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=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="20">
<action android:name="hahaha" />
</intent-filter>
</receiver>
<receiver
android:name=".MyReceiver2"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="19">
<action android:name="hahaha" />
</intent-filter>

</receiver>
</application>

<span style="color:#FF0000;"> <uses-permission android:name="test.permission.TEST"/></span>
</manifest>
然后使用sendOrderedBroadcast(intent,"test.permission.TEST");就可以发送有序广播了,当然发送广播之前还要指定一下接受者的优先级,优先级越高,android:priority指定的数字就越大。取值的范围是:-1000~1000这个就不详细叙述了。

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button send= (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setAction("hahaha");

intent.putExtra("msg","一个简单的消息");
sendOrderedBroadcast(intent,"test.permission.TEST");
}
});
}
}
第一个BroadcastReceiver在接收到广播的时候,如果想要添加一些自己的东西进去,可以先创建一个Bundle对象,并且存入数据。

然后通过setResultExtras(bundle),把这个bundle添加到原来的消息中,

ublic class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"接收到的Intent的Action为:"+intent.getAction()+"\n消息内容是:"+intent.getStringExtra("msg"),Toast.LENGTH_LONG).show();
Bundle bundle=new Bundle();
bundle.putString("first","第一个BroadCast存入的消息!");
setResultExtras(bundle);

}
}


下一个BroadcastReceiver通过getResultExtras可以将信息提取出来。

ublic class MyReceiver2 extends BroadcastReceiver {
public MyReceiver2() {
}

@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
Bundle bundle=getResultExtras(true);
String first=bundle.getString("first");
Toast.makeText(context,"第一个BroadCast存入的消息为:"+first,Toast.LENGTH_LONG).show();
}
}