Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Warning: Exported activity does not require permission 是怎麼回事

編輯:關於 Android 程式設計

在 manifest 裡替自訂 Activity 加上 <intent-filter> 之後, suddenly 就跳出一個編譯警告:Exported activity does not require permission。這個警告看起來有點威脅性,但它其實只是在提醒你一件安全上的事實。

重現情境

使用 SDK 20 建立專案,加上一個自訂 Activity 並在 manifest 宣告:

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity android:name=".MainActivity"
              android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".SecondActivity"
              android:exported="false">
        <intent-filter>
            <action android:name="android.intent.action.CREATE_SHORTCUT" />
        </intent-filter>
    </activity>
</application>

只要 SecondActivity 帶了 <intent-filter>,警告就會出現。

原因

加了 intent-filter,等於宣告這個 Activity 願意回應外部 Intent。系統據此把 android:exported 的預設值判定為 true,也就是其他應用的元件可以直接把它叫起來,而且完全不需要任何權限。警告只是在說:你開了一扇門,卻沒上鎖。

你有兩種處理方向:明確宣告它只在 App 內部使用,或者替它加上權限。

解法

在 Activity 上明確加上 android:exported="false",或者定義並套用權限:

<activity android:name=".SecondActivity"
          android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.CREATE_SHORTCUT" />
    </intent-filter>
</activity>

但這裡剛好相反:exported 必須是 true

這個範例中的 Activity 是為了「建立桌面捷徑」而寫的,功能是讓 Launcher 從外部把它叫起來。若設成 exported="false",捷徑根本加不上去。這時候正確做法是保留 exported="true",並改用權限來限制哪些來源可以呼叫它,警告自然消失。

官方對 android:exported 的定義

Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

The default value depends on whether the activity contains intent filters. The absence of any filters means that the activity can be invoked only by specifying its exact class name. This implies that the activity is intended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the activity is intended for external use, so the default value is "true".

This attribute is not the only way to limit an activity's exposure to other applications. You can also use a permission to limit the external entities that can invoke the activity.

看懂這段就掌握關鍵了:有 intent-filter,預設就是對外開放。所以每次替 Activity 加上 filter 時,都值得自問一句——這個頁面真的需要給別的 App 叫嗎?如果不需要,就明確寫上 android:exported="false";如果需要,就用 android:permission 把來訪者鎖在授權名單裡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved