編輯:關於 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>
這個範例中的 Activity 是為了「建立桌面捷徑」而寫的,功能是讓 Launcher 從外部把它叫起來。若設成 exported="false",捷徑根本加不上去。這時候正確做法是保留 exported="true",並改用權限來限制哪些來源可以呼叫它,警告自然消失。
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 把來訪者鎖在授權名單裡。
自定義控件三部曲之繪圖篇(十二):Paint 之 setXfermode(三)
前面兩篇講完了 setXfermode 的 SRC 系列模式,還剩 DST 系列沒說。這一篇把 DST 相關模式講透,並用幾個完整實例把它們用起來。 一、DST 系列模
仿簡書登入框:自定義 EditText 實作一鍵清空與密碼明文切換
簡書 App 是我很喜歡的一款軟體,這次就來仿一下它的登入框。先看效果: 互動細節有兩個:輸入內容後右側出現叉號可一鍵清空;密碼框右側的眼睛圖示可切換明文/密文顯示。
Android自定義下拉刷新控件(下):為RefreshListView添加加載更多
本篇在自定義下拉刷新控件的基礎上,進一步為它加上「加載更多」的能力,讓列表在滑到底部時能自動觸發加載。先看最終的樣式效果: 1. 創建底部布局layout_foote
BlueStacks 安卓模擬器彈窗的解決辦法
用 BlueStacks 時,不管是下載東西還是開啟程式,都會跳出「One time setup」視窗,很惱人。這個視窗來自它內建的一個應用程式,把它卸掉就清靜了。 Bl