編輯:關於 Android 程式設計
本文介紹 Android 的 Intent 機制,並從源碼角度剖析系統如何完成 Intent 的查詢與比對。
Intent 的中文是「意圖」,而意圖本身是個相當抽象的概念。那麼在 Android 的設計中,要如何把它具象化?系統的做法是用兩類屬性來描述一個 Intent。
主要屬性:Action 與 Data。Action 表示這個 Intent 想表達的動作,Data 則是該動作所操作的資料。
次要屬性:Category、Type、Component 與 Extras。Category 表示類別;Type 表示資料的 MIME 類型;Component 用於直接指定回應者(例如鎖定某個套件下的某個 class);Extras 則用來承載額外資訊。
Android 中的 Intent 主要分成兩類:
Explicit Intent(顯式 Intent):明確指出要啟動哪個 Component,程式碼中可用 setClassName 或 setComponent 鎖定目標。
Implicit Intent(隱式 Intent):不指明目標 Component,而是設定 Action、Data、Category,交由系統篩選出合適的 Component。
先看 Explicit Intent 的兩個寫法:
private void startExplicitIntentWithComponent() {
Intent intent = new Intent();
ComponentName component = new ComponentName("com.example.photocrop", "com.example.photocrop.MainActivity");
intent.setComponent(component);
startActivity(intent);
}
private void startExplicitIntentWithClassName() {
Intent intent = new Intent();
intent.setClassName("com.example.photocrop", "com.example.photocrop.MainActivity");
startActivity(intent);
}
翻源碼會發現,setClassName 其實也是借 ComponentName 來完成顯式 Intent 的:
public Intent setClassName(String packageName, String className) {
mComponent = new ComponentName(packageName, className);
return this;
}
再看 Implicit Intent。這裡讓一個 Activity 標註 Intent Filter,然後寫一段 Intent 去啟動它:
在 AndroidManifest.xml 中為 SendIntentType 加上上述 intent-filter,action 名為「justaction」,category 名為「justcategory」。啟動它的程式碼:
private void startImplictIntent() {
Intent intent = new Intent();
intent.setAction("justaction");
intent.addCategory("justcategory");
startActivity(intent);
}
系統比對 Implicit Intent 時,以 Intent Filter 宣告的三項內容為依據:
先比對 Action。若 Intent 設定的 action 不被 Intent Filter 接受,比對失敗;若 Intent Filter 未設定 Action 或 Action 相同,則成功。
接著檢查 Category,比對方式與 Action 相同,唯一例外是 Category 為 CATEGORY_DEFAULT 的情況。
最後檢查 Data。
從上面的流程不難看出,系統在比對之前,必須先掌握目前所有 Activity 的資訊。這些資訊由 PackageManagerService 在掃描 APK 時收集與管理:
// 處理該 package 的 activity 資訊
N = pkg.activities.size();
r = null;
for (i = 0; i < N; i++) {
PackageParser.Activity a = pkg.activities.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName, pkg.applicationInfo.uid);
mActivities.addActivity(a, "android.intent.action.MAIN");
}
這裡涉及兩個關鍵資料結構:

結合程式碼與上圖可知:mActivities 是 ActivityIntentResolver 型別,作為 PKMS 的成員變數,保存系統中所有與 Activity 相關的資訊。此結構內部另有一個 mActivities 變數,以 ComponentName 為 key,存放 PackageParser.Activity 物件。從 APK 解析出的所有 Activity 資訊(包含 XML 中宣告的 IntentFilter 標籤)都由 PackageParser.Activity 承載。
前面程式碼呼叫的 addActivity 完成了私有資訊的公開化:
public final void addActivity(PackageParser.Activity a, String type) {
final boolean systemApp = isSystemApp(a.info.applicationInfo);
mActivities.put(a.getComponentName(), a);
final int NI = a.intents.size();
for (int j = 0; j < NI; j++) {
PackageParser.ActivityIntentInfo intent = a.intents.get(j);
if (!systemApp && intent.getPriority() > 0 && "android.intent.action.MAIN".equals(type)) {
// 非系統 APK 的 priority 必須為 0
intent.setPriority(0);
}
addFilter(intent);
}
}
接著是 addFilter:
public void addFilter(F f) {
// mFilters 保存所有 IntentFilter 資訊
mFilters.add(f);
int numS = register_intent_filter(f, f.schemesIterator(), mSchemeToFilter, " Scheme: ");
int numT = register_mime_types(f, " Type: ");
if (numS == 0 && numT == 0) {
register_intent_filter(f, f.actionsIterator(), mActionToFilter, " Action: ");
}
if (numT != 0) {
register_intent_filter(f, f.actionsIterator(), mTypedActionToFilter, " TypedAction: ");
}
}
這裡又出現幾個資料結構,型別都是 ArrayMap<String, F[]>(F 為範本參數):
mSchemeToFilter:保存 URI 中與 scheme 相關的 IntentFilter。
mActionToFilter:保存僅設定 Action 條件的 IntentFilter。
mTypedActionToFilter:保存同時設定了 Action 與 Data MIME 類型的 IntentFilter。
接著看 register_intent_filter:
private final int register_intent_filter(F filter, Iteratori, ArrayMap dest, String prefix) { if (i == null) { return 0; } int num = 0; while (i.hasNext()) { String name = i.next(); num++; addFilter(dest, name, filter); } return num; }
又是一個 addFilter,顯然是函式重載:
private final void addFilter(ArrayMapmap, String name, F filter) { F[] array = map.get(name); if (array == null) { array = newArray(2); map.put(name, array); array[0] = filter; } else { final int N = array.length; int i = N; while (i > 0 && array[i-1] == null) { i--; } if (i < N) { array[i] = filter; } else { F[] newa = newArray((N*3)/2); System.arraycopy(array, 0, newa, 0, N); newa[N] = filter; map.put(name, newa); } } }
邏輯並不複雜:若 F 陣列存在就檢查容量,不夠則擴容、夠了就直接填空位;若不存在則建立容量為 2 的陣列,把 filter 放在 0 號位置。
客戶端透過 ApplicationPackageManager 的 queryIntentActivities 向 PackageManagerService 發起查詢:
@Override public ListqueryIntentActivities(Intent intent, int flags) { return queryIntentActivitiesAsUser(intent, flags, mContext.getUserId()); } /** @hide Same as above but for a specific user */ @Override public List queryIntentActivitiesAsUser(Intent intent, int flags, int userId) { try { return mPM.queryIntentActivities(intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags, userId); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } }
真正的實作在 PackageManagerService.java:
public ListqueryIntentActivities(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return Collections.emptyList(); enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); ComponentName comp = intent.getComponent(); if (comp == null) { if (intent.getSelector() != null) { intent = intent.getSelector(); comp = intent.getComponent(); } } if (comp != null) { // Explicit Intent:直接依 component 取得對應的 ActivityInfo final List list = new ArrayList (1); final ActivityInfo ai = getActivityInfo(comp, flags, userId); if (ai != null) { final ResolveInfo ri = new ResolveInfo(); ri.activityInfo = ai; list.add(ri); } return list; } // reader synchronized (mPackages) { final String pkgName = intent.getPackage(); if (pkgName == null) { // Implicit Intent return mActivities.queryIntent(intent, resolvedType, flags, userId); } final PackageParser.Package pkg = mPackages.get(pkgName); if (pkg != null) { // 指定了套件名的 Intent return mActivities.queryIntentForPackage(intent, resolvedType, flags, pkg.activities, userId); } return new ArrayList (); } }
可見 Explicit Intent 的處理相對簡單,重點在 Implicit Intent。它會呼叫 queryIntent:
public ListqueryIntent(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return null; mFlags = flags; return super.queryIntent(intent, resolvedType, (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); }
繼續追進 IntentResolver.java:
public ListqueryIntent(Intent intent, String resolvedType, boolean defaultOnly, int userId) { String scheme = intent.getScheme(); ArrayList finalList = new ArrayList (); // 最多四輪比對 F[] firstTypeCut = null; F[] secondTypeCut = null; F[] thirdTypeCut = null; F[] schemeCut = null; // 若 Intent 帶有 MIME 型別,先收集所有符合該型別的 filter if (resolvedType != null) { int slashpos = resolvedType.indexOf('/'); if (slashpos > 0) { final String baseType = resolvedType.substring(0, slashpos); if (!baseType.equals("*")) { if (resolvedType.length() != slashpos + 2 || resolvedType.charAt(slashpos + 1) != '*') { // 非萬用字元,找出完全相符或 base type 相符的萬用 filter firstTypeCut = mTypeToFilter.get(resolvedType); secondTypeCut = mWildTypeToFilter.get(baseType); } else { // 可匹配該 base type 的所有型別 firstTypeCut = mBaseTypeToFilter.get(baseType); secondTypeCut = mWildTypeToFilter.get(baseType); } // */* 一律適用,但只在 intent type 不是 */* 時才需要 thirdTypeCut = mWildTypeToFilter.get("*"); } else if (intent.getAction() != null) { // Intent 指定了 */*,候選太多,先改用 action 來縮小範圍 firstTypeCut = mTypedActionToFilter.get(intent.getAction()); } } } // 若 Intent 帶有 data URI,先按 scheme 收集 filter, // 之後再對 authority 與 path 逐一細比 if (scheme != null) { schemeCut = mSchemeToFilter.get(scheme); } // 若既無 MIME 型別也無 URI,只比對空資料的 filter if (resolvedType == null && scheme == null && intent.getAction() != null) { firstTypeCut = mActionToFilter.get(intent.getAction()); } FastImmutableArraySet categories = getFastIntentCategories(intent); if (firstTypeCut != null) { buildResolveList(intent, categories, debug, defaultOnly, resolvedType, scheme, firstTypeCut, finalList, userId); } if (secondTypeCut != null) { buildResolveList(intent, categories, debug, defaultOnly, resolvedType, scheme, secondTypeCut, finalList, userId); } if (thirdTypeCut != null) { buildResolveList(intent, categories, debug, defaultOnly, resolvedType, scheme, thirdTypeCut, finalList, userId); } if (schemeCut != null) { buildResolveList(intent, categories, debug, defaultOnly, resolvedType, scheme, schemeCut, finalList, userId); } sortResults(finalList); return finalList; }
真正逐筆比對的工作則落在 buildResolveList 中,這部分原始碼就不在此貼出,有興趣的讀者可以自行追下去看。
三星 Galaxy SIII I9300 使用必看玩機技巧
I9300 相信已有許多人入手,以下彙整一些使用技巧,希望對大家有幫助,若有不足之處歡迎留言補充。 1. 鎖屏方式修改在「設定」-「安全」-「螢幕鎖定」中可取消或改變鎖
微信公眾號怎麼申請?從註冊到送出審核的五個步驟
微信公眾號是公眾平台底下的一支,主要能力是把內容定時推送到追隨者的微信裡——文章、活動、通知,都能即時送達。這也是它成為品牌與個人經營窗口的原因。申請流程第一步:登入微信
Android Service 後台服務完全解析:觀念、生命週期與啟動方式
Service 是 Android 四大元件之一,專門負責在沒有使用者介面的情況下執行較長時間的工作,例如播放音樂、下載檔案、維持長連線。本文從概念、作用、生命週期到啟動
Android 自定義控制項:ToggleButton 開關按鈕
自定義控制項概念自定義 View 可以讓 UI 更靈活。以 ToggleButton 為例,它本質上是一個可在背景圖上滑動的開關,透過繪製與觸摸事件模擬 iOS 風格的切