《Android筆記3.12》 Android 許可權系統

來源:互聯網
上載者:User

標籤:

課程背景:
在 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 許可權了。

《Android筆記3.12》 Android 許可權系統

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.