且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SecurityException:权限被拒绝:通过显式意图启动Activity时

更新时间:2021-07-04 10:25:43

在Android中使用自定义权限是一项相当高级的操作.基本配方是:

Using custom permissions is a fairly advanced thing to do in Android. The basic recipe is:

  1. 确定所需的权限名称.它在设备上必须是唯一的.因此, permission.SHARE_POST 不是一个好选择—添加与您的域名或您要用作应用程序 applicationId 值基础的其他任何内容绑定的前缀.
  2. 在使用权限进行自我保护的应用中,声明< permission> 元素,并使用 android:name 属性保存步骤1中的权限名称.(可选)为其提供一个 android:protectionLevel 属性(例如, signature ,因此只有使用同一签名密钥签名的应用才能一起使用).
  3. 在使用权限进行保护的应用中,在组件上添加 android:permission 属性(例如,< activity> ),其值为您从步骤1开始的权限名称.
  4. 在要与步骤3中的应用进行通信的应用中,添加< uses-permission> 属性,并保留一个 android:name 属性步骤1中的权限名称.
  5. 在这两个应用程序中,将您的 minSdkVersion 设置为21,因为旧版本的自定义权限存在安全问题.
  1. Decide what you want the permission name to be. It needs to be unique on the device. So, permission.SHARE_POST is not a good choice — add a prefix that is tied to your domain name or whatever else it is that you are using as the basis for your apps' applicationId values.
  2. In the app that is defending itself with the permission, declare a <permission> element, with an android:name attribute holding the permission name from step #1. Optionally, give it an android:protectionLevel attribute (e.g., signature, so only apps signed by the same signing key can work together).
  3. In the app that is defending itself with the permission, add an android:permission attribute on the component (e.g., <activity>), with a value of your permission name from step #1.
  4. In the app that is looking to communicate with the app from step #3, add the <uses-permission> attribute, with an android:name attribute holding the permission name from step #1.
  5. In both apps, set your minSdkVersion to 21, as there are security problems with custom permissions on older versions.

如果始终在客户端之前安装防御程序(步骤2和3)(步骤4),则此方法将起作用.如果您希望这些应用程序可以按任一顺序安装,则将上面的第2步替换为:

This will work, if the defender (step #2 and #3) will always be installed before the client (step #4). If you want the apps to be installable in either order, replace step #2 from above with:

  1. 在两个应用程序中 ,声明一个< permission> 元素,并保留一个 android:name 属性步骤1中的权限名称.(可选)为其指定一个 android:protectionLevel 属性(例如, signature ,因此只有使用同一签名密钥签名的应用才能一起使用).另外,请确保两个应用程序始终使用相同的签名密钥进行签名,否则它们将无法定义相同的权限.
  1. In both apps, declare a <permission> element, with an android:name attribute holding the permission name from step #1. Optionally, give it an android:protectionLevel attribute (e.g., signature, so only apps signed by the same signing key can work together). Also, ensure that both apps are always signed by the same signing key, as otherwise they cannot both define the same permission.