Android权限安全(1)自定义,检查,使用权限

时间:2023-08-30 16:08:38

1.自定义权限:

<!-- 定义自定义权限 -->
<permission android:name="com.example.f6k5i8.checkpermission.permission.SAY_HELLO" />

2.检查权限

下面这个hello中的sayHello()函数中检测权限,没有则异常.

 public class Hello {
     public static final String PERMISSION_SAY_HELLO = "com.example.f6k5i8.checkpermission.permission.SAY_HELLO";
     public static void sayHello(Context context){

         int ret = <span style="font-size:18px;color:#ff0000;"><strong>context.checkCallingOrSelfPermission(PERMISSION_SAY_HELLO)</strong></span>;

         if (ret != PackageManager.PERMISSION_GRANTED){//GRANTED是访问 权限
             throw new SecurityException("执行 sayHello 需要有com.example.f6k5i8.checkpermission.permission.SAY_HELLO 权限");
         }
         Log.i("CheckPermission","sayHello()... successed");
     }
 }

3.使用权限

在manifest.xml中

<uses-permission android:name="com.example.f6k5i8.checkpermission.permission.SAY_HELLO" />

在代码中:

Hello.sayHello(this);