您的位置:首页 > 移动开发 > Android开发

Android之定向广播

2016-07-07 18:52 357 查看
Android中当多个应用都接收同一个广播时,会导致很多系统进程同时开启,这会导致系统卡顿。有了ssp我们可以定向的接收或发送某一特定广播达到优化系统的效果。

接收或发送定向广播需要用到android:ssp属性用于匹配URI,ssp代码“scheme-specific part”,意思是代表的东西都在scheme之后出现,如URI是“http://example.com.a”,可以分成scheme部分"http"和ssp部分"//example.com.a"。这里需要特别注意例子中的ssp部分是包含"//"的。

ssp相关:

android:ssp全匹配

android:sspPrefix前缀匹配

android:sspPattern模式匹配

1.接收安装某一特定应用的系统广播

注册方式一:

<receiver android:name="com.example.sspreceiver.PackageAddReceiver">
<intent-filter >
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<data android:scheme="package"
android:ssp="com.tencent.mm"/>
</intent-filter>
</receiver>


注册方式二:

IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addDataScheme("package");
// PatternMatcher.PATTERN_LITERAL相当于ssp
// PatternMatcher.PATTERN_PREFIX相当于sspPrefix
// atternMatcher.PATTERN_SIMPLE_GLOB相当于sspPattern
filter.addDataSchemeSpecificPart("com.tencent.mm",
PatternMatcher.PATTERN_LITERAL);


2.定向发送和接收自定义广播

2.1发送

String RECEIVE_MSG_ACTION = "com.example.sspreceiver.msg_action";

Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(RECEIVE_MSG_ACTION);
Uri data = Uri.parse("msg://com.example.ssp1");
intent.setData(data);
MainActivity.this.sendBroadcast(intent);
}
});

Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent(RECEIVE_MSG_ACTION, Uri
.parse("msg:com.example.ssp2"));
MainActivity.this.sendBroadcast(intent);
}
});


2.2接收

<receiver android:name="com.example.sspreceiver.Ssp1Receiver"
android:process=":ssp1">
<intent-filter >
<action android:name="com.example.sspreceiver.msg_action"/>
<data android:scheme="msg"
android:sspPrefix="//com.example.ssp1"/>
</intent-filter>
</receiver>

<receiver android:name="com.example.sspreceiver.Ssp2Receiver"
android:process=":ssp2">
<intent-filter >
<action android:name="com.example.sspreceiver.msg_action"/>
<data android:scheme="msg"
android:ssp="com.example.ssp2"/>
</intent-filter>
</receiver>


上面注册广播时使用多进程是为了模拟跨应用接收定向广播的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: