在這裏解釋下getType(Uri uri)何時被調用,和
android.intent.category.DEFAULT 的理解。
我們需要什麼時候加android.intent.category.DEFAULT呢?
1、要弄清楚這個問題,首先需要弄明白什麼是implicit(隱藏) intent什麼是explicit(明
確) intent。
Explicit Intent明確的指定了要啓動的Acitivity ,比如以下Java代碼:
Intent intent= new Intent(this, B.class)
Implicit Intent沒有明確的指定要啓動哪個Activity ,而是通過設置一些Intent
Filter來讓系統去篩選合適的Acitivity去啓動。
2、intent到底發給哪個activity,需要進行三個匹配,一個是action,一個是category,
一個是data。
理論上來說,如果intent不指定category,那麼無論intent filter的內容是什麼都應該是
匹配的。但是,如果是implicit intent,android默認給加上一個CATEGORY_DEFAULT,這樣
的話如果intent filter中沒有android.intent.category.DEFAULT這個category的話,匹配
測試就會失敗。所以,如果你的 activity支持接收implicit intent的話就一定要在intent
filter中加入android.intent.category.DEFAULT。
例外情況是:android.intent.category.MAIN和android.intent.category.LAUNCHER的
filter中沒有必要加入android.intent.category.DEFAULT,當然加入也沒有問題。
我們定義的activity如果接受implicit intent的話,intent filer就一定要加上
android.intent.category.DEFAULT這個category。
我的問題就是出現在這裏。忘記在intent-filter中加上了<category
android:name="android.intent.category.DEFAULT" />了這個。
getType(uri uri)這個方法何時被調用呢?
當我們在程序中需要啓動例外的activity時,很多時候我們是使用的隱式調用,即我
們不直接指定要跳轉的Activity,而是爲Intent提供一些相關的參數,讓其自動去和
AndroidManifest.xml中已有的Activity去匹配,而IntentFilter(Intent 過濾器)在xml中
有三個主要的參數:action,categary,data。
我們通過Intent的構造函數或者Intent提供的方法可以指定這個三個參數,如方法有:
intent.setAction(action);
intent.setData(data);
intent.addCategory(category);
等,比如在記事本程序中有:
<intent-filter android:label="@string/resolve_edit">
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.EDIT" />
<action android:name="com.android.notepad.action.EDIT_NOTE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.item/vnd.google.note"
/>
</intent-filter>
我們很容易看出action和category是很容易匹配的,而我們傳的Uri的數據怎麼匹配呢,這
是系統會去調用你定義的ContentProvider中的getType,取得相關的返回值來和上面的data
串進行匹配,當然getType的返回結果你是需要自己去定義的。
但在程序中你也可以自己知道data的類型,就直接匹配了:intent.setType(type);