ContentProvider 提供app间跨进程数据的共享,只是一种机制,本身并不提供数据存储服务,需配合数据库或别的持久化存储使用。
public class MyProvider extends ContentProvider { private static final String AUTHORITY = "com.example.test.provider"; //用于区分不同的ContentProvider private static final UriMatcher sUriMatcher; private static final int CODE1 = 0; private static final int CODE2 = 1; private static final String F1 = "f1"; private static final String F2 = "f2"; static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); //只对这两种uri进行处理 如果匹配上 通过 sUriMatcher.match(uri)可以得到 对应的Code sUriMatcher.addURI(AUTHORITY, F1, CODE1); sUriMatcher.addURI(AUTHORITY, F2, CODE2); } @Override public boolean onCreate() { return true; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { String[] tableCursor = new String[] { "name", "job", "salary" }; MatrixCursor cursor = new MatrixCursor(tableCursor); switch (sUriMatcher.match(uri)) { case CODE1: cursor.addRow(new Object[] { "1111", "111", "11" }); break; case CODE2: cursor.addRow(new Object[] { "2222", "222", "22" }); break; } return cursor; } @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; } }
public class MyService extends Service { private static final String AUTHORITY = "com.example.test.provider"; public static Uri sUri = Uri.parse("content://" + AUTHORITY + "/f2"); @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { 查找 Cursor query = getContentResolver().query(sUri, null, null, null, null, null); if (query!=null){ query.moveToNext(); String s0 = query.getString(0); String s1 = query.getString(1); Log.e("test","s0"+s0+" s1"+s1); } return super.onStartCommand(intent, flags, startId); } }
<service android:name=".MyService" /> <provider android:authorities="com.example.test.provider" android:name=".MyProvider" android:exported="true" android:enabled="true"/>