在上篇博客中我們介紹了自定義ContentProvider,但是遺漏掉了一個方法,那就是getType,自定義ContentProvider一般用不上getType方法,但我們還是一起來探究下這個方法究竟是干什么的?
我們先來看看ContentProvider中對這個類的定義:
/*** Implement this to handle requests for the MIME type of the data at the* given URI. The returned MIME type should start with* <code>vnd.android.cursor.item</code> for a single record,* or <code>vnd.android.cursor.dir/</code> for multiple items.* This method can be called from multiple threads, as described in* <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes* and Threads</a>.** <p>Note that there are no permissions needed for an application to* access this information; if your content provider requires read and/or* write permissions, or is not exported, all applications can still call* this method regardless of their access permissions. This allows them* to retrieve the MIME type for a URI when dispatching intents.** @param uri the URI to query.* @return a MIME type string, or {@code null} if there is no type.*/public abstract @Nullable String getType(@NonNull Uri uri);
注釋說的也算是比較清楚了,根據給定的Uri返回一個MIME類型的數據,如果是單條數據,那么我們的MIME類型應該以vnd.android.cursor.item開頭,如果是多條數據,我們的MIME類型的數據應該以vnd.android.cursor.dir開頭,同時,注釋還很明確的告訴我們,對于沒有訪問該ContentProvider權限的應用依然可以調用它的getType方法。那么我們先來看看什么是MIME,根據維基百科上的解釋,MIME是多用途互聯網郵件擴展(MIME,Multipurpose Internet Mail Extensions)是一個互聯網標準,這話太籠統,大家可以 看看w3c上的解釋http://www.w3school.com.cn/media/media_mimeref.asp,這里有詳細的舉例。
參考網上的信息,getType的作用應該是這樣的,以指定的兩種方式開頭,android可以順利識別出這是單條數據還是多條數據,比如在上篇博客中,我們的查詢結果是一個Cursor,我們可以根據getType方法中傳進來的Uri判斷出query方法要返回的Cursor中只有一條數據還是有多條數據,這個有什么用呢?如果我們在getType方法中返回一個null或者是返回一個自定義的android不能識別的MIME類型,那么當我們在query方法中返回Cursor的時候,系統要對Cursor進行分析,進而得出結論,知道該Cursor只有一條數據還是有多條數據,但是如果我們按照Google的建議,手動的返回了相應的MIME,那么系統就不會自己去分析了,這樣可以提高一丟點的系統性能。基于此,我們上篇自定義的ContentProvider中的getType方法可以這么寫:
@Overridepublic String getType(Uri uri) {int code = matcher.match(uri);switch (code) {case 1:// 查詢多條數據return "vnd.android.cursor.dir/multi";case 2:case 3:// 根據id或者姓名查詢一條數據return "vnd.android.cursor.item/single";}return null;}
MIME前面的一部分我們按照Google的要求來寫,后面一部分就可以根據我們自己的實際需要來寫。還有一種我們可能會很少遇到的情況,我們有可能不知道ContentProvider返回給我們的是什么,這個時候我們可以先調用ContentProvider的getType,根據getType的不同返回值做相應的處理。
就這些,歡迎拍磚指正。