我正在向“Learning Android”学习 - Oreilly - Marko Gargenta。
我在第 11 章(广播接收器)
我跟着这本书,一切正常。但是我有一个关于如何使用自定义权限来限制在单个应用程序中发送和接收广播的问题。
这本书对这个话题很清楚。但我觉得少了点什么。
接收方和发送方如何相互告知不同的权限?
在AndroidManifest.xml
文件中:
<permission
android:name="saleh.yamba.SEND_TIMELINE_NOTIFICATIONS"
android:description="@string/send_timeline_notifications_permission_description"
android:label="@string/send_timeline_notifications_permission_label"
android:permissionGroup="android.permission-group.PERSONAL_INFO"
android:protectionLevel="normal" />
<permission
android:name="saleh.yamba.RECEIVE_TIMELINE_NOTIFICATIONS"
android:description="@string/receive_timeline_notifications_permission_description"
android:label="@string/receive_timeline_notifications_permission_label"
android:permissionGroup="android.permission-group.PERSONAL_INFO"
android:protectionLevel="normal" />
<uses-permission android:name="saleh.yamba.SEND_TIMELINE_NOTIFICATIONS" />
<uses-permission android:name="saleh.yamba.RECEIVE_TIMELINE_NOTIFICATIONS" />
在发送广播的服务中:
Intent intent = new Intent("saleh.yamba.NEW_STATUS");
updaterService.sendBroadcast(intent, "saleh.yamba.RECEIVE_TIMELINE_NOTIFICATIONS");
在这里,发送者发送意图是有saleh.yamba.RECEIVE_TIMELINE_NOTIFICATIONS
权限的,好的,接收者是如何知道这个权限的?
在通过以下方式接收广播的 Activity 中BroadcastReceiver
:
TimelineReceiver receiver;
IntentFilter filter;
protected void onCreate(Bundle savedInstanceState)
{
receiver = new TimelineReceiver();
filter = new IntentFilter("saleh.yamba.NEW_STATUS");
}
protected void onResume()
{
this.registerReceiver(receiver, filter, "saleh.yamba.SEND_TIMELINE_NOTIFICATIONS", null);
}
protected void onPause()
{
this.unregisterReceiver(receiver);
}
private class TimelineReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
//do something.
}
}
在这里,接收者在另一个许可下接收它。好的,
接收方是如何知道的saleh.yamba.RECEIVE_TIMELINE_NOTIFICATIONS
。
接收者部分的代码中没有任何内容表明BroadcastReceiver
只有在接收者有权限时才会调用saleh.yamba.RECEIVE_TIMELINE_NOTIFICATIONS
。