《Android笔记3.12》 Android 权限系统

课程背景:
在 Android 中有非常完善的权限控制机制,开发者需要懂得如何使用,普通用户需要懂得如何分辨,结合起来才能够有效的阻止 Android 平台病毒的传播。

核心内容:
1.定义权限
2.在代码中做权限检查
3.为基本组件添加权限检查

 

请求权限实例

AndroidManifest.xml:

<!--Android安装程序可以根据这个权限来提示用户,程序所需要的权限信息-->
<uses-permission android:name="android.permission.INTERNET"/>

activity_main.xml:

<WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/wv"></WebView>

MainActivity.java:

private WebView wv;

wv = (WebView) findViewById(R.id.wv);
wv.loadUrl("http://www.lanyunwork.com/");//需要访问网页就需要先有互联网访问权限

 

为代码添加权限检查

AndroidManifest.xml:

<permission android:name="com.lanyunwork.l312_checkpermissionincode.permission.SAY_HELLO"/>

<uses-permission android:name="com.lanyunwork.l312_checkpermissionincode.permission.SAY_HELLO"/>

Hello.java:

public class Hello {

    public static final String PERMISSION_SAY_HELLO = "com.lanyunwork.l312_checkpermissionincode.permission.SAY_HELLO";

    public static void sayHello(Context context){

        int checkResult = context.checkCallingOrSelfPermission(PERMISSION_SAY_HELLO);

        if (checkResult != PackageManager.PERMISSION_GRANTED) {
            throw new SecurityException("执行sayHello方法需要有com.lanyunwork.l312_checkpermissionincode.permission.SAY_HELLO权限");
        }

        System.out.println("Hello jikexueyuan");

    }
}

然后在MainActivity中调用Hello.sayHello(this);

如果在AndroidManifest.xml中没有添加权限uses-...,则会报错

 

为基本组件添加权限检查

Activity中配置好权限,原理也是一样的。

在同一个应用中,这个权限并不会起作用。

在其他应用中,想要启动这个程序,就必须添加<uses-...  ,那么Android的安装程序就会知道这个App会需要 XX 权限了。

posted @ 2015-08-07 21:35  暖风叔叔  阅读(204)  评论(0)    收藏  举报