ContentProvider+MatrixCursor进程间应用通信

ContentProvider作为四大组件之一,经常用于进程间数据通信
下面说一下如何使用
1.继承ContentProvider`

package com.example.contentprovider;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.UriMatcher;
import android.database.CharArrayBuffer;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;

import com.orhanobut.logger.Logger;

/**
 * Created by Carson_Hoon 17/6/6.
 */
public class MyProvider extends ContentProvider {

    private Context mContext;
    DBHelper mDbHelper = null;
    SQLiteDatabase db = null;
    public static final String TAG = "MyProvider";
    public static final String AUTOHORITY = "cn.example.contentprovider.MyProvider";
    private String[] config_names = {"name","value"};
    public static final String AREA = "AREA";
    // 设置ContentProvider的唯一标识

    public static final int Config_Code = 1;

    // UriMatcher类使用:在ContentProvider 中注册URI
    private static final UriMatcher mMatcher;
    static{
        mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        // 初始化
        mMatcher.addURI(AUTOHORITY,"config", Config_Code);
        // 若URI资源路径 = content://cn.scu.myprovider/user ,则返回注册码User_Code
        // 若URI资源路径 = content://cn.scu.myprovider/job ,则返回注册码Job_Code
    }

    // 以下是ContentProvider的6个方法

    /**
     * 初始化ContentProvider
     */
    @Override
    public boolean onCreate() {

        mContext = getContext();
        // 在ContentProvider创建时对数据库进行初始化
        // 运行在主线程,故不能做耗时操作,此处仅作展示
        //mDbHelper = new DBHelper(getContext());
        //db = mDbHelper.getWritableDatabase();

        return true;
    }

    /**
     * 添加数据
     */

    @Override
    public Uri insert(Uri uri, ContentValues values) {

        // 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名
        // 该方法在最下面
        String table = getTableName(uri);

        // 向该表添加数据
        //db.insert(table, null, values);

        // 当该URI的ContentProvider数据发生变化时,通知外界(即访问该ContentProvider数据的访问者)
       // mContext.getContentResolver().notifyChange(uri, null);

//        // 通过ContentUris类从URL中获取ID
//        long personid = ContentUris.parseId(uri);
//        System.out.println(personid);
        return uri;
        }

    /**
     * 查询数据
     */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名
        // 该方法在最下面
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("config",Context.MODE_PRIVATE);
        MatrixCursor ret = new MatrixCursor(config_names);
        Object[] values = new Object[config_names.length];
        if(mMatcher.match(uri) == Config_Code){
            Logger.t(TAG).i("Config_Code: "+Config_Code);
            values[0] = AREA;
            values[1] = sharedPreferences.getString(AREA,"000000");
            ret.addRow(values);
            return ret;
        }
        return  null;

//        // 通过ContentUris类从URL中获取ID
//        long personid = ContentUris.parseId(uri);
//        System.out.println(personid);
        // 查询数据
       // return db.query(table,projection,selection,selectionArgs,null,null,sortOrder,null);
    }

    /**
     * 更新数据
     */
    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // 由于不展示,此处不作展开
        return 0;
    }

    /**
     * 删除数据
     */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // 由于不展示,此处不作展开
        return 0;
    }

    @Override
    public String getType(Uri uri) {

        // 由于不展示,此处不作展开
        return null;
    }

    /**
     * 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名
     */
    private String getTableName(Uri uri){
        String tableName = null;
        switch (mMatcher.match(uri)) {
            case Config_Code:
                tableName = DBHelper.CONFIG_TABLE_NAME;
                break;
        }
        return tableName;
        }
    }


2.AndroidManifest文件中配置

<provider android:name="com.example.contentprovider.MyProvider"
            android:authorities="cn.example.contentprovider.MyProvider "
            android:exported="true"
            />

3.使用

Uri configUri = null;
        Cursor mCursor = null;
        try {
            configUri = Uri.parse("content://cn.example.contentprovider.MyProvider /config");
            mCursor = context.getContentResolver().query(configUri, null, null, null, null);
            if (mCursor != null) {
                while (mCursor.moveToNext()) {
                    String name = mCursor.getString(mCursor.getColumnIndex("name"));
                    String value = mCursor.getString(mCursor.getColumnIndex("value"));
                    Logger.t(TAG).i("name=" + name);
                    Logger.t(TAG).i("value=" + value);
                }
                mCursor.close();
            } else {
                Logger.t(TAG).i("failed find config");
            }
            // 设置URI
            // 插入表中数据
            ContentValues values = new ContentValues();
            values.put("AREA", "000001");
            // 获取ContentResolver
            ContentResolver resolver = context.getContentResolver();
            // 通过ContentResolver 根据URI 向ContentProvider中插入数据
            resolver.insert(configUri, values);
        }catch (Exception e){
            Logger.t(TAG).e("failed find config: "+e.toString());
            if(mCursor != null){
                mCursor.close();
            }
            MyApplication.getInstance()
                    .setAuthAidlReturn(TIME, "exception: ");
        }

你可能感兴趣的:(Android)