当我们的的应用数据需要给外界访问的时候,就需要跨进程通信。在Android中,如果进行数据共享,ContentProvider是最好的选择,它的实现很简单,并且底层封装好了Binder对象用于处理远程连接。在另一个应用中,如果想要共享当前应用的数据,只需要获取一个ContentResolver对象,然后通过Uri匹配就可以与当前应用的ContentProvider建立连接,之后对ContentResolver进行增删改查操作其实就是对远程数据进行增删改查操作。接下来将介绍SQLiteOpenHelper,SQLiteDatabase,ContentProvider,ContentResolver,UriMather类,来了解整个共享数据的过程。
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
this(context, name, factory, version, null);
}
这个方法用来创建一个用于打开,创建,管理数据库的SQLiteOpenHelper对象。需要注意的是,这个方法会快速的执行但是并不会立即创建数据库,只有在开发者第一次调用的getWriteableDatabase或者getReadbleDatabase方法时才会打开或者创建数据库。参数解析如下:
db.beginTransaction();
* try {
* ...
* db.setTransactionSuccessful();
* } finally {
* db.endTransaction();
* }
public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
public abstract int delete(@NonNull Uri uri, @Nullable String selection,
@Nullable String[] selectionArgs);
public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
@Nullable String selection, @Nullable String[] selectionArgs);
public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
@Nullable String selection, @Nullable String[] selectionArgs,
@Nullable String sortOrder);
private static final int PEOPLE = 1;
private static final int PEOPLE_ID = 2;
private static final int PEOPLE_PHONES = 3;
private static final int PEOPLE_PHONES_ID = 4;
private static final int PEOPLE_CONTACTMETHODS = 7;
private static final int PEOPLE_CONTACTMETHODS_ID = 8;
private static final int DELETED_PEOPLE = 20;
private static final int PHONES = 9;
private static final int PHONES_ID = 10;
private static final int PHONES_FILTER = 14;
private static final int CONTACTMETHODS = 18;
private static final int CONTACTMETHODS_ID = 19;
private static final int CALLS = 11;
private static final int CALLS_ID = 12;
private static final int CALLS_FILTER = 15;
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static
{
sURIMatcher.addURI("contacts", "people", PEOPLE);
sURIMatcher.addURI("contacts", "people/#", PEOPLE_ID);
sURIMatcher.addURI("contacts", "people/#/phones", PEOPLE_PHONES);
sURIMatcher.addURI("contacts", "people/#/phones/#", PEOPLE_PHONES_ID);
sURIMatcher.addURI("contacts", "people/#/contact_methods", PEOPLE_CONTACTMETHODS);
sURIMatcher.addURI("contacts", "people/#/contact_methods/#", PEOPLE_CONTACTMETHODS_ID);
sURIMatcher.addURI("contacts", "deleted_people", DELETED_PEOPLE);
sURIMatcher.addURI("contacts", "phones", PHONES);
sURIMatcher.addURI("contacts", "phones/filter/*", PHONES_FILTER);
sURIMatcher.addURI("contacts", "phones/#", PHONES_ID);
sURIMatcher.addURI("contacts", "contact_methods", CONTACTMETHODS);
sURIMatcher.addURI("contacts", "contact_methods/#", CONTACTMETHODS_ID);
sURIMatcher.addURI("call_log", "calls", CALLS);
sURIMatcher.addURI("call_log", "calls/filter/*", CALLS_FILTER);
sURIMatcher.addURI("call_log", "calls/#", CALLS_ID);
}
public String getType(Uri url)
{
int match = sURIMatcher.match(url);
switch (match)
{
case PEOPLE:
return "vnd.android.cursor.dir/person";
case PEOPLE_ID:
return "vnd.android.cursor.item/person";
... ...
return "vnd.android.cursor.dir/snail-mail";
case PEOPLE_ADDRESS_ID:
return "vnd.android.cursor.item/snail-mail";
default:
return null;
}
}
package com.cw.contentprovider;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.util.Log;
import java.io.File;
/**
* Created by Myy on 2016/7/19.
*/
public class SqliteManager extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "test.db";
private final static String USER_NAME = "user", BOOK_NAME = "book";
private final static String CREATE_TABLE_USER = "create table if not exists " + USER_NAME + "(_id integer primary key," + "name text);";
private final static String CREATE_TABLE_BOOK = "create table if not exists " + BOOK_NAME + "(_id integer primary key," + "name text);";
public SqliteManager(Context context) {
super(context.getApplicationContext(), DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE_BOOK);
db.execSQL(CREATE_TABLE_USER);
} catch (Exception err) {
Log.i("exception", err.getMessage());
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
db.execSQL("delete from user");
db.execSQL("delete from book");
Log.i("onUpgrade","更新");
}
}
}
package com.cw.contentprovider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* Created by Myy on 2016/7/20.
*/
public class DatabaseManager {
private static SqliteManager manager;
private DatabaseManager() {
}
private static class DatabaseManagerHolder {
private static DatabaseManager instance = new DatabaseManager();
}
public static DatabaseManager getInstance(Context context) {
if (manager == null) {
manager = new SqliteManager(context.getApplicationContext());
}
return DatabaseManagerHolder.instance;
}
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs
, String groupBy, String having, String orderBy) {
SQLiteDatabase sb = getDatabase();
Cursor cursor = sb.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
return cursor;
}
public int insert(String table, String nullColumnHack, ContentValues values) {
SQLiteDatabase sb = getDatabase();
long result = sb.insert(table, nullColumnHack, values);
return (int) result;
}
private SQLiteDatabase getDatabase() {
return manager.getWritableDatabase();
}
}
package com.cw.contentprovider;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by Myy on 2016/7/20.
*/
public class TestContentProvider extends ContentProvider {
private final static int USER = 0, BOOK = 1;
private final static String authority = "com.hy.blog.contentProvider";
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
matcher.addURI(authority, "user", USER);
matcher.addURI(authority, "book", BOOK);
}
private DatabaseManager manager;
@Override
public boolean onCreate() {
manager = DatabaseManager.getInstance(getContext());
Log.i("onCreate", Thread.currentThread().getName());
return false;
}
@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Log.i("query", Thread.currentThread().getName());
String table = getTableName(uri);
if (table != null)
return manager.query(table, projection, selection, selectionArgs, null, null, sortOrder);
return null;
}
private String getTableName(Uri uri) {
int code = matcher.match(uri);
switch (code) {
case USER:
return "user";
case BOOK:
return "book";
default:
return null;
}
}
@Nullable
@Override
public String getType(Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
Log.i("insert", Thread.currentThread().getName());
String table = getTableName(uri);
manager.insert(table, null, values);
return uri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
package com.cw.contentprovider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private Uri bookUri, userUri;
private ContentResolver resolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bookUri = Uri.parse("content://com.hy.blog.contentProvider/book");
userUri = Uri.parse("content://com.hy.blog.contentProvider/user");
resolver = getContentResolver();
new Thread(new Runnable() {
@Override
public void run() {
Log.i("mainActivity", Thread.currentThread().getName());
insert();
query();
}
}).start();
}
private void query() {
Cursor userCursor = resolver.query(userUri, null, null, null, null);
while (userCursor.moveToNext()) {
int id = userCursor.getInt(userCursor.getColumnIndex("_id"));
String name = userCursor.getString(userCursor.getColumnIndex("name"));
Log.i("user", "id:" + id + ",name:" + name);
}
userCursor.close();
Cursor bookCursor = resolver.query(bookUri, null, null, null, null);
while (bookCursor.moveToNext()) {
int id = bookCursor.getInt(bookCursor.getColumnIndex("_id"));
String name = bookCursor.getString(bookCursor.getColumnIndex("name"));
Log.i("user", "id:" + id + ",name:" + name);
}
bookCursor.close();
}
private void insert() {
ContentValues userValues1 = new ContentValues();
userValues1.put("_id", 1);
userValues1.put("name", "hy");
ContentValues userValues2 = new ContentValues();
userValues2.put("_id", 2);
userValues2.put("name", "hd");
resolver.insert(userUri, userValues1);
resolver.insert(userUri, userValues2);
Log.i("user", "insert success");
ContentValues bookValues1 = new ContentValues();
bookValues1.put("_id", 222);
bookValues1.put("name", "hlm");
ContentValues bookValues2 = new ContentValues();
bookValues2.put("_id", 333);
bookValues2.put("name", "shz");
resolver.insert(bookUri, bookValues1);
resolver.insert(bookUri, bookValues2);
Log.i("book", "insert success");
}
}
public SqliteManager(Context context) {
super(context.getApplicationContext(), DATABASE_NAME, null, 2);//把1改成2
}
---------文章写自:HyHarden---------
--------博客地址:http://blog.csdn.net/qq_25722767/article/details/51895992-----------