内容提供器(Content Provider)
简介
内容提供器(Content Provider)主要用于在不同的应用程序之间实现数据共享的功能,它提供了一套完整的机制,允许一个程序访问另一个程序中的数据,同时还能保证被访数据的安全性。
Android权限机制详解
在AndroidManifest.xml文件中添加权限
<uses-permission android:name=""/>
权限列表查看地址
http://developer.android.com/reference/android/Manifest.permission.html
代码中的权限申请
// 第一步判断:
ContextCompat.checkSelfPermission()
//两个参数,第一个Context,第二个权限名称
//第二步申请授权:
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CALL_PHONE},1)
//第三步验证授权:
onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults)
访问其他程序中的数据
对于应用程序来说,如果想要访问内容提供器中的共享数据,需要借助ContentResolver类
可以通过Context中的getContentResolver()方法获取到该实例。
Uri uri = Uri.parse("content://com.example.app.provider/table1");
Cursor cursor = getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);
//遍历
if(cursor.moveToFirst()){
do{
}while(cursor.moveToNext)
}
读取通讯录中的联系人和手机号码
<uses-permission android:name="android.permission.READ_CONTACTS"/>
ListView contactsView = findViewById(R.id.contacts_view);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, contactsList);
contactsView.setAdapter(adapter);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
} else {
readContacts();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readContacts();
} else {
Toast.makeText(this, "you denied the premission", Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
private void readContacts() {
Cursor cursor = null;
try {
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
@SuppressLint("Range")
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
@SuppressLint("Range")
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(name + "\n" + number);
}
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
创建自己的内容提供器
创建MyProvider继承ContentProvider
public class MyProvider extends ContentProvider {
public static final int BOOK_DIR =0;
public static final int BOOK_ITEM = 1;
private static UriMatcher uriMatcher;
public static final String AUTHORITY = "com.example.providertest.provider";
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY,"book",BOOK_DIR);
uriMatcher.addURI(AUTHORITY,"book/#",BOOK_ITEM);
}
@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) {
switch (uriMatcher.match(uri)){
case BOOK_DIR:
// 查询book表中的所有数据
break;
case BOOK_ITEM:
// 查询book表中的单条数据
break;
default:
break;
}
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
switch (uriMatcher.match(uri)){
case BOOK_DIR:
return "vnd.android.cursor.dir/vnd.com.example.providertest.provider.book";
case BOOK_ITEM:
return "vnd.android.cursor.item/vnd.com.example.providertest.provider.book";
default:
break;
}
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;
}
}
在AndroidManifest.xml中
<provider
android:name=".DatabaseProvider"
android:authorities="com.example.providertest.provider"
android:enabled="true"
android:exported="true"></provider>
新建DatabaseProvider继承ContentProvider
public class DatabaseProvider extends ContentProvider {
public static final int BOOK_DIR = 0;
public static final int BOOK_ITEM = 1;
private MydbHelper mydbHelper;
private static UriMatcher uriMatcher;
public static final String AUTHORITY = "com.example.providertest.provider";
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "book", BOOK_DIR);
uriMatcher.addURI(AUTHORITY, "book/#", BOOK_ITEM);
}
public DatabaseProvider() {
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = mydbHelper.getReadableDatabase();
int deleteRows = 0;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
deleteRows = db.delete("Book", selection, selectionArgs);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
deleteRows = db.delete("Book", "id = ?", new String[]{bookId});
break;
default:
break;
}
return deleteRows;
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)){
case BOOK_DIR:
return "vnd.android.cursor.dir/vnd.com.example.providertest.provider.book";
case BOOK_ITEM:
return "vnd.android.cursor.item/vnd.com.example.providertest.provider.book";
default:
break;
}
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mydbHelper.getReadableDatabase();
Uri uriReturn = null;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
case BOOK_ITEM:
long newBookId = db.insert("Book", null, values);
uriReturn = Uri.parse("content://" + AUTHORITY + "/book/" + newBookId);
break;
default:
break;
}
return uriReturn;
}
@Override
public boolean onCreate() {
mydbHelper = new MydbHelper(getContext(), "BookStore.db", null, 2);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Cursor cursor = null;
SQLiteDatabase db = mydbHelper.getReadableDatabase();
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
cursor = db.query("Book", projection, selection, selectionArgs, null, null, sortOrder);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
cursor = db.query("Book", projection, "id = ?", new String[]{bookId}, null, null, sortOrder);
break;
default:
break;
}
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = mydbHelper.getReadableDatabase();
int updateRows = 0;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
updateRows = db.update("Book", values, null, null);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
updateRows = db.update("Book", values, "id = ?", new String[]{bookId});
break;
default:
break;
}
return updateRows;
}
}
主活动中使用getContentResolver()增删改查处理
//增
findViewById(R.id.button1).setOnClickListener(v -> {
ContentValues values = new ContentValues();
values.put("name", "yyyyyyyypppppppp");
values.put("author", "tt111tt");
values.put("pages", 900);
values.put("price", 10.99);
Uri uri = Uri.parse("content://com.example.providertest.provider/book");
Uri insert = getContentResolver().insert(uri, values);
newId = insert.getPathSegments().get(1);
});
//删
findViewById(R.id.button3).setOnClickListener(v -> {
Uri uri = Uri.parse("content://com.example.providertest.provider/book/" + newId);
getContentResolver().delete(uri,null,null);
});
//改
findViewById(R.id.button2).setOnClickListener(v -> {
ContentValues values = new ContentValues();
values.put("name", "zybao");
Uri uri = Uri.parse("content://com.example.providertest.provider/book/" + newId);
getContentResolver().update(uri,values,null,null);
});
//查
findViewById(R.id.button4).setOnClickListener(v -> {
Uri uri = Uri.parse("content://com.example.providertest.provider/book");
Cursor cursor2 =getContentResolver().query(uri,null,null,null,null);
if (cursor2.moveToFirst()) {
do {
String name = cursor2.getString(cursor2.getColumnIndexOrThrow("name"));
Log.d("cursor2", "book name is " + name);
} while (cursor2.moveToNext());
}
});
标签:String,提供,uri,Uri,BOOK,内容,Android,null,public
From: https://www.cnblogs.com/zybao/p/16908298.html