以编程方式检查广播接收器权限

Posted

技术标签:

【中文标题】以编程方式检查广播接收器权限【英文标题】:Checking Broadcast Receiver Permission Programatic 【发布时间】:2012-08-11 04:49:21 【问题描述】:

我有一个广播接收器用于我的 C2DM(旧)消息传递,例如

    <receiver android:name=".C2DMRegistrationReceiver">
           <!-- Receive the actual message -->
          <intent-filter>
              <action android:name="com.google.android.c2dm.intent.RECEIVE" />
              <category android:name="com.test" />
          </intent-filter>
          <!-- Receive the registration id -->
          <intent-filter>
              <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
              <category android:name="com.test" />
          </intent-filter>
         <intent-filter>
              <action android:name="REGISTRY_RETRY" />
              <category android:name="com.test" />
          </intent-filter>
    </receiver>

出于安全原因,您应该为此接收者声明一个权限,例如

<receiver android:name=".C2DMRegistrationReceiver" permission="com.google.android.c2dm.permission.SEND">

我的问题是我的 3. Intent Filter 没有收到呼叫,因为我强制执行 com.google.android.c2dm.permission.SEND 权限。

所以我的问题:有没有办法为一个广播接收器定义 2 个权限,或者我可以在我的 onReceive 代码中为调用者强制执行权限?

我试过了

  private boolean checkC2DMPermission(Context context) 
    String permission = "com.google.android.c2dm.permission.SEND";
    context.enforceCallingPermission(permission, "Keine C2DM Permission");
    return true;
  

我还测试了 context.checkCallingPermission(permission) 它的 -1 用于 C2DM 注册意图。 Enforce 给了我一个 SecurityException。

【问题讨论】:

为什么不简单地将您用于REGISTRY_RETRY 的逻辑移动到单独的BroadcastReceiver 中?如果您希望在此代码和 C2DM 代码之间拥有公共代码,请使用继承或组合。 是的,这肯定是最简单的解决方案。我只是好奇,对这个问题有点固执。 【参考方案1】:

我知道这个问题很老,但我遇到了同样的问题,这出现在谷歌搜索中,所以我们开始吧。

简短的回答是你不能。

提到的methods 用于执行 IPC,例如使用 AIDL 的bound service。

广播接收器未执行 IPC,因此您无法从广播接收器获取发送者权限。

要强制执行权限,您必须在清单中声明广播接收器的权限。这是可行的,因为 Android 在将其传递给接收者之前会强制执行所需的权限。

权限对于接收器中的所有操作都是通用的。为了解决这个问题,您可以按照@CommonsWare 的建议将广播接收器拆分为单独的类。

【讨论】:

以上是关于以编程方式检查广播接收器权限的主要内容,如果未能解决你的问题,请参考以下文章

从Intent服务发送短信 - 无法接收广播以检查是否发送了短信

如何在没有权限的android 6中使用广播接收器启动应用程序

四大组件之BroadcastReceiver-使用权限和常用的系统广播

Android 广播 - 使用权限发送和接收

Android本地广播的使用

具有权限级别签名的Android广播接收器不接收广播