自定义内容提供者getType(Uri uri) 方法详解

来源:互联网 发布:python和java和php 编辑:程序博客网 时间:2024/06/05 23:55
10我们先来看看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 * Processes * and Threads. * *

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的不同返回值做相应的处理。

0 0