1、在AndroidManifast.xml添加
<provider android:name="com.hsae.userprofile.provide.UserProfileProvider"
android:authorities="com.hsae.userprofile"
android:exported="true"
android:multiprocess="true"
android:permission="com.hsae.userprofile.provide.UserProfileProvider"> <-- 访问权限 -->
</provider>
1、创建 UserProfileProvider 继承 ContentProvider
package com.userprofile.provide;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import java.util.HashMap;
public class UserProfileProvider extends ContentProvider {
private final static String TAG = UserProfileProvider.class
.getSimpleName();
/**
* 数据库名称
*/
private final static String DB_NAME = "userprofile.db";
/**
* 存储默认账户信息的表
*/
private final static String DB_TABLE_USER_DEFAULT = "userDefault";
/**
* 存储用户一信息的表
*/
private final static String DB_TABLE_USER_ONE = "userDefaultOne";
/**
* 存储用户二信息的表
*/
private final static String DB_TABLE_USER_TWO = "userDefaultTwo";
/**
* 数据库版本号
*/
private final static int DB_VERSION = 1;
//数据库语法,创建默认账户
private static final String DB_CREATE_DEFAULT = "create table if not exists " +
DB_TABLE_USER_DEFAULT + " ("
+ UserProfileGlobal.ID + " integer primary key autoincrement, " + UserProfileGlobal.NAME
+ " text not null, " + UserProfileGlobal.VALUE + " text not null);";
private static final String DB_CREATE_ONE = "create table if not exists " + DB_TABLE_USER_ONE
+ " ("
+ UserProfileGlobal.ID + " integer primary key autoincrement, " + UserProfileGlobal.NAME
+ " text not null, " + UserProfileGlobal.VALUE + " text not null);";
private static final String DB_CREATE_TOW = "create table if not exists " + DB_TABLE_USER_TWO
+ " ("
+ UserProfileGlobal.ID + " integer primary key autoincrement, " + UserProfileGlobal.NAME
+ " text not null, " + UserProfileGlobal.VALUE + " text not null);";
private DBHelper dbHelper = null;
private ContentResolver resolver = null;
/**
* URI matcher used to recognize URIs sent by applications
*/
//初始化UriMatcher 用于匹配Uri
private static final UriMatcher sURIMatcher = new UriMatcher(
UriMatcher.NO_MATCH);
//注册需要的Uri:
static {
sURIMatcher.addURI(UserProfileGlobal.AUTHORITY, "userDefault", UserProfileGlobal
.ITEM_DEFAULT);
sURIMatcher.addURI(UserProfileGlobal.AUTHORITY, "userDefault/#", UserProfileGlobal
.ITEM_DEFAULT_ID);
sURIMatcher.addURI(UserProfileGlobal.AUTHORITY, "userDefaultOne", UserProfileGlobal
.ITEM_ONE);
sURIMatcher.addURI(UserProfileGlobal.AUTHORITY, "userDefaultOne/#", UserProfileGlobal
.ITEM_ONE_ID);
sURIMatcher.addURI(UserProfileGlobal.AUTHORITY, "userDefaultTwo", UserProfileGlobal
.ITEM_TWO);
sURIMatcher.addURI(UserProfileGlobal.AUTHORITY, "userDefaultTwo/#", UserProfileGlobal
.ITEM_TWO_ID);
}
private static final HashMap<String, String> HaseUserProfileProjectionMap;
static {
HaseUserProfileProjectionMap = new HashMap<String, String>();
HaseUserProfileProjectionMap.put(UserProfileGlobal.ID, UserProfileGlobal.ID);
HaseUserProfileProjectionMap.put(UserProfileGlobal.NAME, UserProfileGlobal.NAME);
HaseUserProfileProjectionMap.put(UserProfileGlobal.VALUE, UserProfileGlobal.VALUE);
}
@Override
public boolean onCreate() {
Context context = getContext();
resolver = context.getContentResolver();
dbHelper = new DBHelper(context, DB_NAME, null, DB_VERSION);
Log.i(TAG, "HaseSettings Provider Create");
return true;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
if (!(sURIMatcher.match(uri) == UserProfileGlobal.ITEM_DEFAULT || sURIMatcher.match(uri)
== UserProfileGlobal.ITEM_ONE || sURIMatcher.match(uri) == UserProfileGlobal
.ITEM_TWO)) {
throw new IllegalArgumentException("Error Uri: " + uri);
}
SQLiteDatabase db = dbHelper.getWritableDatabase();
//与已经注册的Uri进行匹配:
if (sURIMatcher.match(uri) == UserProfileGlobal.ITEM_DEFAULT) {
long id = db.insert(DB_TABLE_USER_DEFAULT, UserProfileGlobal.ID, values);
if (id < 0) {
throw new SQLiteException("Unable to insert " + values + " for "
+ uri);
}
String name = values.getAsString(UserProfileGlobal.NAME);
Uri newUri = Uri.withAppendedPath(UserProfileGlobal.CONTENT_URI_DEFAULT, name);
resolver.notifyChange(newUri, null);
return newUri;
} else if (sURIMatcher.match(uri) == UserProfileGlobal.ITEM_ONE) {
long id = db.insert(DB_TABLE_USER_ONE, UserProfileGlobal.ID, values);
if (id < 0) {
throw new SQLiteException("Unable to insert " + values + " for "
+ uri);
}
String name = values.getAsString(UserProfileGlobal.NAME);
Uri newUri = Uri.withAppendedPath(UserProfileGlobal.CONTENT_URI_ONE, name);
resolver.notifyChange(newUri, null);
return newUri;
} else if (sURIMatcher.match(uri) == UserProfileGlobal.ITEM_TWO) {
long id = db.insert(DB_TABLE_USER_TWO, UserProfileGlobal.ID, values);
if (id < 0) {
throw new SQLiteException("Unable to insert " + values + " for "
+ uri);
}
String name = values.getAsString(UserProfileGlobal.NAME);
Uri newUri = Uri.withAppendedPath(UserProfileGlobal.CONTENT_URI_TWO, name);
resolver.notifyChange(newUri, null);
return newUri;
}
return null;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Log.i(TAG, "HaseSettingsProvider.query: " + uri);
SQLiteDatabase db = dbHelper.getReadableDatabase();
SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
String limit = null;
switch (sURIMatcher.match(uri)) {
case UserProfileGlobal.ITEM_DEFAULT: {
sqlBuilder.setTables(DB_TABLE_USER_DEFAULT);
sqlBuilder.setProjectionMap(HaseUserProfileProjectionMap);
break;
}
case UserProfileGlobal.ITEM_DEFAULT_ID: {
String id = uri.getPathSegments().get(1);
sqlBuilder.setTables(DB_TABLE_USER_DEFAULT);
sqlBuilder.setProjectionMap(HaseUserProfileProjectionMap);
sqlBuilder.appendWhere(UserProfileGlobal.ID + "=" + id);
break;
}
case UserProfileGlobal.ITEM_ONE: {
sqlBuilder.setTables(DB_TABLE_USER_ONE);
sqlBuilder.setProjectionMap(HaseUserProfileProjectionMap);
break;
}
case UserProfileGlobal.ITEM_ONE_ID: {
String id = uri.getPathSegments().get(1);
sqlBuilder.setTables(DB_TABLE_USER_ONE);
sqlBuilder.setProjectionMap(HaseUserProfileProjectionMap);
sqlBuilder.appendWhere(UserProfileGlobal.ID + "=" + id);
break;
}
case UserProfileGlobal.ITEM_TWO: {
sqlBuilder.setTables(DB_TABLE_USER_TWO);
sqlBuilder.setProjectionMap(HaseUserProfileProjectionMap);
break;
}
case UserProfileGlobal.ITEM_TWO_ID: {
String id = uri.getPathSegments().get(1);
sqlBuilder.setTables(DB_TABLE_USER_TWO);
sqlBuilder.setProjectionMap(HaseUserProfileProjectionMap);
sqlBuilder.appendWhere(UserProfileGlobal.ID + "=" + id);
break;
}
default:
throw new IllegalArgumentException("Error Uri: " + uri);
}
Cursor cursor = sqlBuilder.query(db, projection, selection,
selectionArgs, null, null,
TextUtils.isEmpty(sortOrder) ? UserProfileGlobal.DEFAULT_SORT_ORDER
: sortOrder, limit);
cursor.setNotificationUri(resolver, uri);
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count = 0;
switch (sURIMatcher.match(uri)) {
case UserProfileGlobal.ITEM_DEFAULT: {
count = db.update(DB_TABLE_USER_DEFAULT, values, selection, selectionArgs);
break;
}
case UserProfileGlobal.ITEM_DEFAULT_ID: {
String id = uri.getPathSegments().get(1);
count = db.update(DB_TABLE_USER_DEFAULT, values, UserProfileGlobal.ID
+ "="
+ id
+ (!TextUtils.isEmpty(selection) ? " and (" + selection
+ ')' : ""), selectionArgs);
break;
}
case UserProfileGlobal.ITEM_ONE: {
count = db.update(DB_TABLE_USER_ONE, values, selection, selectionArgs);
break;
}
case UserProfileGlobal.ITEM_ONE_ID: {
String id = uri.getPathSegments().get(1);
count = db.update(DB_TABLE_USER_ONE, values, UserProfileGlobal.ID
+ "="
+ id
+ (!TextUtils.isEmpty(selection) ? " and (" + selection
+ ')' : ""), selectionArgs);
break;
}
case UserProfileGlobal.ITEM_TWO: {
count = db.update(DB_TABLE_USER_TWO, values, selection, selectionArgs);
break;
}
case UserProfileGlobal.ITEM_TWO_ID: {
String id = uri.getPathSegments().get(1);
count = db.update(DB_TABLE_USER_TWO, values, UserProfileGlobal.ID
+ "="
+ id
+ (!TextUtils.isEmpty(selection) ? " and (" + selection
+ ')' : ""), selectionArgs);
break;
}
default:
throw new IllegalArgumentException("Error Uri: " + uri);
}
String name = values.getAsString(UserProfileGlobal.NAME);
if (sURIMatcher.match(uri) == UserProfileGlobal.ITEM_DEFAULT || sURIMatcher.match(uri) ==
UserProfileGlobal.ITEM_DEFAULT_ID) {
Uri uri_update = Uri.withAppendedPath(UserProfileGlobal.CONTENT_URI_DEFAULT, name);
resolver.notifyChange(uri_update, null);
} else if (sURIMatcher.match(uri) == UserProfileGlobal.ITEM_ONE || sURIMatcher.match(uri)
== UserProfileGlobal
.ITEM_ONE_ID) {
Uri uri_update = Uri.withAppendedPath(UserProfileGlobal.CONTENT_URI_ONE, name);
resolver.notifyChange(uri_update, null);
} else if (sURIMatcher.match(uri) == UserProfileGlobal.ITEM_TWO || sURIMatcher.match(uri)
== UserProfileGlobal
.ITEM_TWO_ID) {
Uri uri_update = Uri.withAppendedPath(UserProfileGlobal.CONTENT_URI_TWO, name);
resolver.notifyChange(uri_update, null);
}
return count;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count = 0;
switch (sURIMatcher.match(uri)) {
case UserProfileGlobal.ITEM_DEFAULT: {
count = db.delete(DB_TABLE_USER_DEFAULT, selection, selectionArgs);
break;
}
case UserProfileGlobal.ITEM_DEFAULT_ID: {
String id = uri.getPathSegments().get(1);
count = db.delete(DB_TABLE_USER_DEFAULT,
UserProfileGlobal.ID
+ "="
+ id
+ (!TextUtils.isEmpty(selection) ? " and ("
+ selection + ')' : ""), selectionArgs);
break;
}
case UserProfileGlobal.ITEM_ONE: {
count = db.delete(DB_TABLE_USER_ONE, selection, selectionArgs);
break;
}
case UserProfileGlobal.ITEM_ONE_ID: {
String id = uri.getPathSegments().get(1);
count = db.delete(DB_TABLE_USER_ONE,
UserProfileGlobal.ID
+ "="
+ id
+ (!TextUtils.isEmpty(selection) ? " and ("
+ selection + ')' : ""), selectionArgs);
break;
}
case UserProfileGlobal.ITEM_TWO: {
count = db.delete(DB_TABLE_USER_TWO, selection, selectionArgs);
break;
}
case UserProfileGlobal.ITEM_TWO_ID: {
String id = uri.getPathSegments().get(1);
count = db.delete(DB_TABLE_USER_TWO,
UserProfileGlobal.ID
+ "="
+ id
+ (!TextUtils.isEmpty(selection) ? " and ("
+ selection + ')' : ""), selectionArgs);
break;
}
default:
throw new IllegalArgumentException("Error Uri: " + uri);
}
resolver.notifyChange(uri, null);
return count;
}
@Override
public String getType(Uri uri) {
switch (sURIMatcher.match(uri)) {
case UserProfileGlobal.ITEM_DEFAULT:
return UserProfileGlobal.CONTENT_TYPE;
case UserProfileGlobal.ITEM_DEFAULT_ID:
return UserProfileGlobal.CONTENT_ITEM_TYPE;
case UserProfileGlobal.ITEM_ONE:
return UserProfileGlobal.CONTENT_TYPE;
case UserProfileGlobal.ITEM_ONE_ID:
return UserProfileGlobal.CONTENT_ITEM_TYPE;
case UserProfileGlobal.ITEM_TWO:
return UserProfileGlobal.CONTENT_TYPE;
case UserProfileGlobal.ITEM_TWO_ID:
return UserProfileGlobal.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Error Uri: " + uri);
}
}
@Override
public Bundle call(String method, String name, Bundle extras) {
Log.i(TAG, "HaseSettingsProvider.call: " + method);
if (method.equals(UserProfileGlobal.METHOD_GET_VALUE)) {
return getValue(name);
} else if (method.equals(UserProfileGlobal.METHOD_PUT_VALUE)) {
return putValue(name, extras);
} else {
}
throw new IllegalArgumentException("Error method call: " + method);
}
/**
* 获取设置值
*
* @param name
* @return
*/
private Bundle getValue(String name) {
Cursor mCursor = query(UserProfileGlobal.getAccontUri(), new String[]{UserProfileGlobal.ID,
UserProfileGlobal.NAME, UserProfileGlobal.VALUE}, UserProfileGlobal.NAME
+ " = ?",
new String[]{name}, UserProfileGlobal.DEFAULT_SORT_ORDER);
if (mCursor.getCount() > 0) {
mCursor.moveToFirst();
Bundle bundle = new Bundle();
bundle.putCharSequence(UserProfileGlobal.VALUE,
mCursor.getString(mCursor.getColumnIndex(UserProfileGlobal.VALUE)));
Log.i(TAG, "SettingProvide getValue name:" + name + ", value:" + bundle
.getCharSequence(UserProfileGlobal.VALUE));
mCursor.close();
return bundle;
}
mCursor.close();
return null;
}
/**
* 修改设置值
*
* @param name
* @param extras
* @return
*/
private Bundle putValue(String name, Bundle extras) {
Cursor mCursor = query(UserProfileGlobal.getAccontUri(), new String[]{UserProfileGlobal.ID,
UserProfileGlobal.NAME, UserProfileGlobal.VALUE}, UserProfileGlobal.NAME
+ " = ?",
new String[]{name}, UserProfileGlobal.DEFAULT_SORT_ORDER);
ContentValues values = new ContentValues();
values.put(UserProfileGlobal.NAME, name);
values.put(UserProfileGlobal.VALUE, extras.getString(UserProfileGlobal.VALUE));
Log.i(TAG, "SettingProvide putValue name:" + name + ", value:" + extras.getString
(UserProfileGlobal.VALUE));
if (mCursor.getCount() > 0) {
mCursor.moveToFirst();
String id = mCursor.getString(mCursor.getColumnIndex(UserProfileGlobal.ID));
Uri uri = Uri.withAppendedPath(UserProfileGlobal.getAccontUri(), id);
update(uri, values, null, null);
} else {
insert(UserProfileGlobal.getAccontUri(), values);
}
mCursor.close();
return null;
}
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE_DEFAULT);
db.execSQL(DB_CREATE_ONE);
db.execSQL(DB_CREATE_TOW);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_USER_DEFAULT);
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_USER_ONE);
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_USER_TWO);
onCreate(db);
}
}
}
3、UserProfileGlobal 类
package com.userprofile.provide;
import android.net.Uri;
import com.hsae.autosdk.userprofile.UserProfileConst;
public class UserProfileGlobal {
/* uri 主体 */
public static final String AUTHORITY = "com.hsae.userprofile";
/* 默认账户 */
private static String accountDefault = "/userDefault";
/* 账户1 */
private static String accountOne = "/userDefaultOne";
/* 账户2 */
private static String accountTwo = "/userDefaultTwo";
/**
* 数据库列表,索引ID
*/
public final static String ID = "_id";
/**
* 数据库列表,名称
*/
public final static String NAME = "name";
/**
* 数据库列表,值
*/
public final static String VALUE = UserProfileConst.VALUE;
/* Match Code */
public static final int ITEM_DEFAULT = 1;
public static final int ITEM_DEFAULT_ID = 2;
public static final int ITEM_ONE = 3;
public static final int ITEM_ONE_ID = 4;
public static final int ITEM_TWO = 5;
public static final int ITEM_TWO_ID = 6;
/* 默认账户Uri */
public static final Uri CONTENT_URI_DEFAULT = UserProfileConst.CONTENT_URI_DEFAULT;
/* 账户一Uri */
public static final Uri CONTENT_URI_ONE = UserProfileConst.CONTENT_URI_ONE;
/* 账户二Uri */
public static final Uri CONTENT_URI_TWO = UserProfileConst.CONTENT_URI_TWO;
/* Default sort order */
public static final String DEFAULT_SORT_ORDER = "_id asc";
/* Call Method */
public static final String METHOD_GET_VALUE = UserProfileConst.METHOD_GET_VALUE;
public static final String METHOD_PUT_VALUE = UserProfileConst.METHOD_PUT_VALUE;
/* MIME */
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/com.hsae" +
".userprofile";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/com.hsae" +
".userprofile";
public static Uri getAccontUri() {
return UserProfileConst.getAccontUri();
}
}
4、创建 公共类 UserProfileConst ,可供其他app访问
package com.autosdk.userprofile;
import android.net.Uri;
public class UserProfileConst {
/* userprofile 数据库 start */
/* uri 主体 */
private static final String AUTHORITY = "com.hsae.userprofile";
/* 默认账户 */
private static String accountDefault = "/userDefault";
/* 账户1 */
private static String accountOne = "/userDefaultOne";
/* 账户2 */
private static String accountTwo = "/userDefaultTwo";
/* 默认账户Uri */
public static final Uri CONTENT_URI_DEFAULT = Uri.parse("content://" + AUTHORITY
+ "/" + accountDefault);
/* 账户一Uri */
public static final Uri CONTENT_URI_ONE = Uri.parse("content://" + AUTHORITY
+ "/" + accountOne);
/* 账户二Uri */
public static final Uri CONTENT_URI_TWO = Uri.parse("content://" + AUTHORITY
+ "/" + accountTwo);
/**
* 数据库列表,值
*/
public final static String VALUE = "value";
/* Call Method */
public static final String METHOD_GET_VALUE = "getValue";
public static final String METHOD_PUT_VALUE = "putValue";
public static Uri getAccontUri() {
return CONTENT_URI_DEFAULT;
}
/* userprofile 数据库 end */
}
5、封装统一的调用接口UserProfile
package com.autosdk.userprofile;
import android.content.Context;
import android.os.Bundle;
public class UserProfile {
private static String TAG = UserProfile.class.getSimpleName();
private Context mContext;
private static UserProfile mInstance;
public static UserProfile getInstance(Context context) {
if (mInstance == null) {
synchronized (UserProfile.class) {
if (mInstance == null) {
mInstance = new UserProfile(context);
}
}
}
return mInstance;
}
public UserProfile(Context context) {
this.mContext = context;
}
/**
* 存储数据
*
* @param key 参数key, 每一个key唯一value
* @param value 参数value 需要存储的参数
*/
public void saveValue(String key, Object value) {
Bundle bundle = new Bundle();
bundle.putCharSequence(UserProfileConst.VALUE, value + "");
mContext.getContentResolver().call(UserProfileConst.getAccontUri(), UserProfileConst.METHOD_PUT_VALUE, key, bundle);
}
/**
* 读取数据
*
* @param key 参数key, 每一个key唯一value
* @param def 参数def 默认值
*/
public String getStringValue(String key, String def) {
Bundle bundle = mContext.getContentResolver().call(UserProfileConst.getAccontUri(), UserProfileConst.METHOD_GET_VALUE, key,
null);
if (bundle != null) {
return bundle.getString(UserProfileConst.VALUE);
}
return def;
}
/**
* 读取数据
*
* @param key 参数key, 每一个key唯一value
* @param def 参数def 默认值
*/
public boolean getBooleanValue(String key, boolean def) {
Bundle bundle = mContext.getContentResolver().call(UserProfileConst.getAccontUri(), UserProfileConst.METHOD_GET_VALUE, key,
null);
if (bundle != null) {
return bundle.getString(UserProfileConst.VALUE).equalsIgnoreCase("true") ? true : false;
}
return def;
}
/**
* 读取数据
*
* @param key 参数key, 每一个key唯一value
* @param def 参数def 默认值
*/
public int getIntegerValue(String key, int def) {
Bundle bd = mContext.getContentResolver().call(UserProfileConst.getAccontUri(),
UserProfileConst.METHOD_GET_VALUE, key, null);
if (bd != null) {
return Integer.parseInt(bd.getString(UserProfileConst.VALUE));
}
return def;
}
/**
* 读取数据
*
* @param key 参数key, 每一个key唯一value
* @param def 参数def 默认值
*/
public float getFloatValue(String key, float def) {
Bundle bd = mContext.getContentResolver().call(UserProfileConst.getAccontUri(),
UserProfileConst.METHOD_GET_VALUE, key, null);
if (bd != null) {
return Float.parseFloat(bd.getString(UserProfileConst.VALUE));
}
return def;
}
/**
* 读取数据
*
* @param key 参数key, 每一个key唯一value
* @param def 参数def 默认值
*/
public double getDoubleValue(String key, double def) {
Bundle bd = mContext.getContentResolver().call(UserProfileConst.getAccontUri(),
UserProfileConst.METHOD_GET_VALUE, key, null);
if (bd != null) {
return Double.parseDouble(bd.getString(UserProfileConst.VALUE));
}
return def;
}
}
6、调用方法:
UserProfile userProfile = UserProfile.getInstance(context);
userProfile.saveValue(keyValue, value );
userProfile.getBooleanValue(keyValue, defValue);