• 【Android 四大组件之Content Provider】一文吃透Content Provider 内容提供者


    作者:半身风雪
    上一节:一文看懂Service
    简介:在Android组件中最基本也是最为常见的四大组件:

    • Activity
    • Service服务
    • Content Provider内容提供者
    • BroadcastReceiver广播接收器


    一、什么是Content Provider

    Content Provider 是安卓系统中四大组件之一,被称为内容提供者,内容提供者组件通过请求从一个应用程序向其他的应用程序提供数据。这些请求由类 ContentResolver 的方法来处理。内容提供者可以使用不同的方式来存储数据。数据可以被存放在数据库,文件,甚至是网络。

    img

    有时候需要在应用程序之间共享数据,就一定要借助ContentResolver类,通过getContent -Resolver获取实例,在ContentResolver中提供了一系CRUD(增删改查)的方法进行操作其中。

    • insert,添加数据
    • update,更新数据
    • delete,删除数据
    • query,查询数据

    多数情况下数据被存储在 SQLite 数据库。

    内容提供者被实现为类 ContentProvider 类的子类。需要实现一系列标准的 API,以便其他的应用程序来执行事务。

    二、内容URI

    要查询内容提供者,你需要指定URI的格式来指定查询字符串:

    😕//<data_type>/

    部分说明
    prefix前缀:一直被设置为content://
    authority授权:指定内容提供者的名称,例如联系人,浏览器等。第三方的内容提供者可以是全名,如:cn.programmer.statusprovider
    data_type数据类型:这个表明这个特殊的内容提供者中的数据的类型。例如:你要通过内容提供者Contacts来获取所有的通讯录,数据路径是people,那么URI将是下面这样:content://contacts/people
    id这个指定特定的请求记录。例如:你在内容提供者Contacts中查找联系人的ID号为5,那么URI看起来是这样:content://contacts/people/5

    三、创建内容提供者

    这里描述创建自己的内容提供者的简单步骤。

    • 首先,你需要继承类 ContentProvider 来创建一个内容提供者类。
    • 其次,你需要定义用于访问内容的你的内容提供者URI地址。
    • 接下来,你需要创建数据库来保存内容。通常,Android 使用 SQLite 数据库,并在框架中重写 onCreate() 方法来使用 SQLiteOpenHelper 的方法创建或者打开提供者的数据库。当你的应用程序被启动,它的每个内容提供者的 onCreate() 方法将在应用程序主线程中被调用。
    • 最后,使用<provider…/>标签在 AndroidManifest.xml 中注册内容提供者。

    我们还需要重新ContentProvider 的六个方法:

    img

    • onCreate():当提供者被启动时调用。
    • query():该方法从客户端接受请求。结果是返回指针(Cursor)对象。
    • insert():该方法向内容提供者插入新的记录。
    • delete():该方法从内容提供者中删除已存在的记录。
    • update():该方法更新内容提供者中已存在的记录。
    • getType():该方法为给定的URI返回元数据类型。

    四、代码示例

    1. 在Activity 中添加两个点击按钮事件,分别实现添加和获取功能。

        public void onClickAddName(View view) {
      
              ContentValues contentValues = new ContentValues();
              contentValues.put(Students.NAME, ((EditText) findViewById(R.id.add_edi)).getText().toString());
      
              System.out.println(contentValues);
      
              Uri uri = getContentResolver().insert(
                      Students.CONTENT_URI, contentValues);
      
              System.out.println(uri);
      
              Toast.makeText(getBaseContext(),
                      uri.toString(), Toast.LENGTH_LONG).show();
      
      
          }
      
          @SuppressLint("Range")
          public void onClickRetrieveName(View view) {
      // Retrieve student records
              Cursor cursor = getContentResolver().query(Students.CONTENT_URI, null, "name", null, null);
              if (cursor.moveToFirst()) {
                  do {
                      ((TextView) findViewById(R.id.get_edi)).setText(cursor.getString(cursor.getColumnIndex(Students.NAME)));
      
                      Toast.makeText(this,
                              cursor.getString(cursor.getColumnIndex(Students._ID)) +
                                      ", " + cursor.getString(cursor.getColumnIndex(Students.NAME)),
                              Toast.LENGTH_SHORT).show();
                  } while (cursor.moveToNext());
              }
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
    2. 创建一个Students 文件,继承自ContentProvider,并重新它的6个方法。我这里增、删、改、查都已经写好了,可以直接使用。

    public class Students extends ContentProvider {
    
        static final String PROVIDER_NAME = "com.traveleasy.activitydemo";
        static final String URL = "content://" + PROVIDER_NAME + "/students";
        static final Uri CONTENT_URI = Uri.parse(URL);
    
    
        static final String _ID = "_id";
        static final String NAME = "name";
    
        private static HashMap<String, String> STUDENTS_PROJECTION_MAP;
    
        static final int STUDENTS = 1;
        static final int STUDENT_ID = 2;
    
        static final UriMatcher uriMatcher;
    
        static {
            uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
            uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
            uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);
        }
    
        /**
         * 数据库特定常量声明
         */
        private SQLiteDatabase db;
        static final String DATABASE_NAME = "College";
        static final String STUDENTS_TABLE_NAME = "students";
        static final int DATABASE_VERSION = 1;
        static final String CREATE_DB_TABLE =
                " CREATE TABLE " + STUDENTS_TABLE_NAME +
                        " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        " name TEXT NOT NULL);";
    
        /**
         * 创建和管理提供者内部数据源的帮助类.
         */
        private static class DatabaseHelper extends SQLiteOpenHelper {
            DatabaseHelper(Context context) {
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }
    
            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL(CREATE_DB_TABLE);
            }
    
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME);
                onCreate(db);
            }
        }
    
    
        @Override
        public boolean onCreate() {
            Context context = getContext();
            DatabaseHelper dbHelper = new DatabaseHelper(context);
    
            /**
             * 如果不存在,则创建一个可写的数据库。
             */
            db = dbHelper.getWritableDatabase();
            return db != null;
        }
    
        @Nullable
        @Override
        public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
            SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
            qb.setTables(STUDENTS_TABLE_NAME);
    
            switch (uriMatcher.match(uri)) {
                case STUDENTS:
                    qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
                    break;
    
                case STUDENT_ID:
                    qb.appendWhere(_ID + "=" + uri.getPathSegments().get(1));
                    break;
    
                default:
                    throw new IllegalArgumentException("Unknown URI " + uri);
            }
    
            if (sortOrder == null || sortOrder == "") {
                /**
                 * 默认按照学生姓名排序
                 */
                sortOrder = NAME;
            }
            Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    
            /**
             * 注册内容URI变化的监听器
             */
            c.setNotificationUri(getContext().getContentResolver(), uri);
            return c;
        }
    
        @Nullable
        @Override
        public String getType(@NonNull Uri uri) {
            switch (uriMatcher.match(uri)) {
                /**
                 * 获取所有学生记录
                 */
                case STUDENTS:
                    return "vnd.android.cursor.dir/vnd.example.students";
    
                /**
                 * 获取一个特定的学生
                 */
                case STUDENT_ID:
                    return "vnd.android.cursor.item/vnd.example.students";
    
                default:
                    throw new IllegalArgumentException("Unsupported URI: " + uri);
            }
        }
    
        @Nullable
        @Override
        public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
            /**
             * 添加新学生记录
             */
            long rowID = db.insert(STUDENTS_TABLE_NAME, "", values);
    
            /**
             * 如果记录添加成功
             */
    
            if (rowID > 0) {
                Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
                getContext().getContentResolver().notifyChange(_uri, null);
                return _uri;
            }
            throw new SQLException("Failed to add a record into " + uri);
        }
    
    
        @Override
        public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
            int count = 0;
    
            switch (uriMatcher.match(uri)) {
                case STUDENTS:
                    count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);
                    break;
    
                case STUDENT_ID:
                    String id = uri.getPathSegments().get(1);
                    count = db.delete(STUDENTS_TABLE_NAME, _ID + " = " + id +
                            (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
                    break;
    
                default:
                    throw new IllegalArgumentException("Unknown URI " + uri);
            }
    
            getContext().getContentResolver().notifyChange(uri, null);
            return count;
        }
    
        @Override
        public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
            int count = 0;
    
            switch (uriMatcher.match(uri)) {
                case STUDENTS:
                    count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs);
                    break;
    
                case STUDENT_ID:
                    count = db.update(STUDENTS_TABLE_NAME, values, _ID + " = " + uri.getPathSegments().get(1) +
                            (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
                    break;
    
                default:
                    throw new IllegalArgumentException("Unknown URI " + uri);
            }
            getContext().getContentResolver().notifyChange(uri, null);
            return count;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    1. 使用<provider…/>标签在 AndroidManifest.xml 清单文件中注册内容提供者,这里的authorities 可以随便填,但是必须得和申明的URI 一致。
    <provider
                android:authorities="com.traveleasy.activitydemo"
                android:name=".Students"
                android:exported="true"
                />
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 在activity.xml 文件中创建一个文本输入框和一个label 数据展示框
    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:id="@+id/add_edi"
        android:hint="请输入人员"
        />
    
    <TextView
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:id="@+id/get_edi"
        android:gravity="center_vertical"
        android:hint="这里会自动获取"
        />
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    运行结果:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FItDkbpN-1656396162878)(/Users/tiger/Library/Application%20Support/typora-user-images/image-20220628134848801.png)]

    总结

    总的一句:内容提供器是应用程序之间共享数据的接口,Android系统将这种机制应用到方方面面。比如:联系人提供器专为不同应用程序提供联系人数据;设置提供器专为不同应用程序提供系统配置信息,包括内置的设置应用程序等。

  • 相关阅读:
    面试官:熔断和降级有什么区别?
    太强了,全面解析缓存应用经典问题
    Layui快速入门之第八节 表格渲染与属性的使用
    Spring Boot整合Swagger
    硬件混音 饱和失真问题 网页资料
    hexo建站新手入门
    尚医通(一)
    MySQL的故事——MySQL架构与历史
    C2基础设施威胁情报对抗策略
    c语言必背100代码,C语言代码大全(c语言必背项目代码)
  • 原文地址:https://blog.csdn.net/u010755471/article/details/125501154