0

我正在向“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

4

1 回答 1

0

接收者部分的代码中没有任何内容表明只有在发送者拥有 saleh.yamba.RECEIVE_TIMELINE_NOTIFICATIONSpermission 时才会调用 BroadcastReceiver。

就在这里。你传递saleh.yamba.RECEIVE_TIMELINE_NOTIFICATIONSregisterReceiver().

具体来说,您使用的是 的四参数版本registerReceiver(),其中第三个参数是“字符串命名广播者必须持有的权限才能向您发送 Intent。如果为空,则不需要权限。”

于 2013-07-19T19:06:32.117 回答