ContentProvider可以在进程之间进行数据共享;记录一下关于数据库共享的信息
简单使用是比较简单的;
1,在app A 中;创建自己的ContentProvider
/** * Created by changquan on 2018/9/12. * 自定义内容提供者实现数据库共享 */ public class MyProvider extends ContentProvider { private static final int SUCCESS = 1; /** 判断Uri规则 */ static UriMatcher mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { mUriMatcher.addURI("com.roi.sell_electricity", "account", SUCCESS); //uri规则可自己定义,但一定和清单文件一直 } @Override public boolean onCreate() { return false; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { int code = mUriMatcher.match(uri); if (SUCCESS == code) { Co_GreenDaoBeanDao dao = GreenDaoHelper.getDaoSession().getCo_GreenDaoBeanDao(); return dao.getDatabase().rawQuery("select * from "+dao.getTablename(),null); }else { throw new IllegalArgumentException("路径不正确"); } } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { return null; } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } }
2,注册
<!-- 注册内容提供者数据 --> <provider android:exported="true" android:name=".MyProvider" android:authorities="com.roi.sell_electricity" > </provider>
3,在另一个app B 上面获取共享数据库里面的数据
ContentResolver resolver = getContentResolver(); Uri uri = Uri.parse("content://com.roi.sell_electricity/account"); Cursor cursor = resolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { String username = cursor.getString(cursor.getColumnIndex("username")); String age = cursor.getString(cursor.getColumnIndex("AGE")); LogUtil.e("TestActivity","username:" + username + "age:" + age); } cursor.close();