Android許可權控制之自訂許可權_Android

來源:互聯網
上載者:User

天哪,這篇文章終於說道如何自訂許可權了,左盼右盼,其實這個自訂許可權相當easy。為了方便敘述,我這邊會用到兩個app作為例子示範。

Permission App: used to define a new permission
這個作為定義許可權的App,我稱之為Permission App.
Client App: used to access the specified activity of Permission App
這個作為訪問上述自訂許可權的App,我稱之為Client App

先看如何寫Permission App

第一步

Permission App很簡單,它的任務就是定一個Permission,使用< permission>標籤即可,我們假設內容如下:

複製代碼 代碼如下:

<permission android:name="custom.permission.STARTACTIVITY" android:description="@string/permission_dcr" android:protectionLevel=signatureOrSystem android:label="label"></permission>

第二步

然後在定一個Activity,這個Activity很簡單就是展示下一行字,如”Hello from Custiom Permission Activity!”這裡就不詳述。

第三步

最重要的地方:我們需要為這個Activity指明存取權限,許可權即為我們剛申請的許可權,這個需要同樣需要在AndroidManifest.xml檔案中標識,如下:

複製代碼 代碼如下:

<activity
        android:name="com.example.custompermission.MainActivity"
        android:label="@string/app_name" android:permission="custom.permission.STARTACTIVITY"> 
</activity>

這個Activity於是就被打上了必須使用” custom.permission.STARTACTIVITY”許可權才能訪問的印記。

接著寫Client App

至於如何寫Client App,那就so so so … easy了,只需兩步:

第一步

在AndroidManifest.xml檔案中首先申請許可權,如下:

複製代碼 代碼如下:

<uses-permission android:name="custom.permission.STARTACTIVITY"/>

第二步

訪問Permission App表明需要該許可權的Activity,代碼如下:

複製代碼 代碼如下:

Intent in = new Intent(); 
in.setClassName("com.example.custompermission", "com.example.custompermission.MainActivity"); 
startActivity(in);

大功告成

我們可以測試下效果,首先安裝Permission App,然後接著安裝Client App,結果如下:

點擊之後

另外我曾經在Android Permission許可權機制引子提到過Protection Level問題,這邊我同樣測試下這個Protection Level,下面結果中Y表示可以正常訪問,N則表示不可以訪問。

需要注意的是,使用自訂Permission的activity如果設定了:

複製代碼 代碼如下:

<activity
        android:name="com.example.custompermission.MainActivity"
        android:label="@string/app_name" android:permission="custom.permission.STARTACTIVITY"> 
<intent-filter> 
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" /> 
</intent-filter>

那就不能從Launcher中啟動該App,因為只有你的Launcher必須使用了uses-permission去請求擷取custom.permission.STARTACTIVITY許可權,事實上你的Launcher是不具備已經請求自訂許可權的。

Launcher會報:Application is not installed on your phone. 的錯誤.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.