一、問題描述
最近切換到一個新的項目中,查看代碼的時候,發現AndroidManifest.xml清單文件有一堆的警告
- Service警告
<service
android:name=".oyp.CSDNService"
android:enabled="true"
android:exported="true" />
錯誤描述 : Exported service does not require permission
信息提示信息如下:
Exported service does not require permission
Inspection Info : Exported services(serviceswhich either set exported=true or contain an intent-filter and does not specify exported=false) should define a permission that an entity must have in order to launch the service or bind to it. Without this ,any application can use this service .
翻譯後
導出的服務不需要權限
檢查信息:可以被外部訪問的服務(設置Exported=true或包含intent過濾器且未指定Exported=false的服務)應定義實體必須擁有的權限,才能啓動服務或綁定到服務。沒有這個,任何應用程序都可以使用這個服務。
- Receiver警告
<receiver android:name=".oyp.AReceiver">
<intent-filter>
<action android:name="com.oyp.ACTIOON_CSDN" />
</intent-filter>
</receiver>
錯誤描述: Exported receiver does not require permission
詳細錯誤如下所示:
Exported receiver does not require permission
Inspection Info : Exported receivers(receivers which either set exported=true or contain an intent-filter and does not specify exported=false) should define a permission that an entity must have in order to launch the receiver or bind to it. Without this ,any application can use this receiver.
翻譯
導出的接收器不需要權限
檢驗信息:可以被外部訪問的接收者(設置Exported=true或包含意圖過濾器且未指定Exported=false的接收者)應定義實體必須擁有的權限,以便啓動接收者或綁定到接收者。沒有這個,任何應用程序都可以使用這個接收器。
二、修復問題
上面問題的本質原因是:這是一個可以被外部訪問的service,需要使用權限來限制外部訪問。service默認是exported=“false”,receiver默認是exported=“true”
因此可以採取兩個方式來修復該問題。
2.1 把可被外面訪問改成不可被外面訪問
android:exported=“false”
這種方法是限制外部訪問,自然不需要權限了
但是得看你自己的實際業務,如果這些receiver和service 需要被外部訪問的話,這個方式就不行。
2.2 聲明權限
2.2.1 定義一個自定義的permission
<permission
android:name="com.oyp.permission.CSDN_TEST_PERMISSION"
android:protectionLevel="normal" />
android:protectionLevel 爲權限的安全級別,不同的級別對應着不同的權限獲取行爲,這裏按從低到高的順序有以下四種:
- normal:普通權限,優先級最低,需要在應用安裝時提示用戶授權,否則無法安裝,而一旦允許,後面APP在運行過程中將一直擁有該權限。
- dangerous:危險權限,比如通訊錄,短信等,該權限在6.0以下,表現行爲與normal無異,但在6.0及以上需要在APP運行過程中動態申請。
- signature:獲取該權限,必須保證請求方和接收方使用同一個簽名文件,在安裝時默認授權,不會提示用戶。該權限一般用於系統內置應用,或者同一個公司的多個APP中。
- signatureOrSystem:相比signature多了一個條件,當請求方爲系統應用時默認擁有該權限,一般用於系統內置應用。
2.2.2 使用權限
在service節點添加下面的代碼
android:permission="com.oyp.permission.CSDN_TEST_PERMISSION"
這樣就不會產生警告了。而且保證了其他的應用只有聲明瞭權限才能直接訪問此Receiver。
好吧,得將項目所有的相似警告整改一遍,是個比較操蛋的事情!
三、閱讀系統源代碼
最好的方式是閱讀系統源代碼,爲什麼我們寫APP 需要使用那麼多權限,也是一樣的道理。
可以參考下面這篇博客,瞭解原理。
四、參考鏈接
- https://blog.csdn.net/lwwgtm/article/details/8834500
- https://stackoverflow.com/questions/11462936/exported-activity-does-not-require-permission-when-attempting-to-launch-from-a/11526028#11526028
- https://www.jianshu.com/p/dbec9f59a019
- https://www.cnblogs.com/liuzhipenglove/p/7102889.html
- https://www.cnblogs.com/aimqqroad-13/p/8927179.html
- https://blog.csdn.net/weixin_37077539/article/details/56279789