通过内容提供器,可以实现在不同程序中数据共享,同时保证数据安全性。
先了解一下运行时权限,是6.0引入的新特性。Android现在把权限分为两种,一种是普通权限,另一种是危险权限。普通权限系统会自动授权,而危险权限则需要运行时由用户授权。
危险权限如上图所示,有9组24项,其他则都为普通权限,当用户授予了一项权限,其存在的那一组权限都会被授予。
运行时申请权限
首先第一步判断用户是否已经授过权,调用ContextCompat.checkSelfPermission()方法,第一个参数为Context对象,第二个为权限名,将返回值与PackageManager.PERMISSION_GRANTED比较,相等则授过权:并执行相应操作;不等则向用户申请权限,调用ActivityCompat.requestPermissions()方法,第一个参数为Activity对象,第二个为多个权限名(String类型数组,可以申请多个权限),第三个时(int)请求码,后续操作需要使用,唯一即可。调用完申请方法后,会弹出一个对话框让用户选择是否授权,无论结果怎样,都会回调到onRequestPermissionsResult(),第一个是之前的请求码,第二个是权限名,第三个是int型数组,是各个权限申请的结果。在函数中使用swtich…case…实现相应的请求码执行相应的操作,每一个case对应申请码以实现每次申请都有相应的操作,之后再case中判断各个权限结果是否等于PackageManager.PERMISSION以判断是否授权进行相应操作,以下是相应案例执行打电话操作(CALL_PHONE危险权限):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.call_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.
permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){ //判断是否授权
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},1); //申请权限
}else{
call();
}
}
});
}
@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){ //如果授权
call();
}else{
Toast.makeText(this,"you reject the permission!",Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
public void call(){ //封装打电话代码
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:1008611"));
startActivity(intent);
}
在AndroiMainfest.xml中申明权限:
查:
从表中查数据
Cursor cursor = getContentResolver().query(uri,列名,"column1=?",为条件提供的具体的值,排序方式)
就类似于sql语句的 select 列 from 表 where x="";
然后通过遍历cursor对象来读出数据
while(cursor.moveToNext){
String column1 = cursor.getString(cursor.getColumnIndex("列名1"));
int column1 = cursor.getInt(cursor.getColumnIndex("列名2"));
}
增:
ContentValues values = new ContentValues();
values.put("列名1“,”“);
values.put("列名2”,“”);
getContentResolver().insert(uri,values);
改:
ContentValues values = new ContentValues();
values.put("列名1“,”“);
getContentResolver().updater(uri,values,"column1=?,column2=?","new String{"条件的值1","条件的值2"});
删:
getContentResolver().delete(uri,"column1=?",new String{"条件1"});
一个具体例子,读取联系人:
package com.example.hankzz.contactproject;
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ArrayAdapter adapter;
private List contactlist = new ArrayList<>();
private ListView contact_views;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contact_views = (ListView) findViewById(R.id.contact_views);
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,contactlist);
contact_views.setAdapter(adapter);
if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_CONTACTS) !=
PackageManager.PERMISSION_GRANTED){ //判断用户是否授权
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},
1); //申请权限
}else{
readContact();
}
}
public void readContact(){
Cursor cursor = null;
//通过getContentResolver().query()方法查询联系人数据,联系人Uri对象是已经封装好了
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
if(cursor != null){
while(cursor.moveToNext()){ //遍历查询到的数据
String name = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
contactlist.add(name+"\n"+number);
}
adapter.notifyDataSetChanged();
}
}
@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){
readContact();
}else{
Toast.makeText(this,"no permission",Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
}
自己的内容提供器ContentProvider
首先要明白这其中的原理,首先通过ContentProvdier给自己的程序提供外部访问接口,这样其他程序才可以通过ContentResolver来访问,ContentResolver通过Uri对象(Authority+path)(“content://com.example.hankzz.databaseproject/table1”或content://com.example.hankzz.databaseproject/table1/1" 这是我的程序)中的Authority来确认访问到哪个程序,在调用增删改查方法,这些方法其实是在调用ContentProvidre中的增删改查方法,具体实现由ContentProvider实现。但访问到了程序怎么指定哪个表,这也是通过Uri对象实现,当然也可以指定某一列,只需要在表后加 /列号 就可以。但这样在ContentProvider中怎么去判断呢,这就需要UriMatcher的match方法,把Uri匹配一个int值,这样在增删改查时把传过来的uri也match一下根据swtich case 去执行相应访问不同表的情况
所以,我们现在来创一个试试看。
先在包中右键选择new->other->ContentProvider,创建一个子类MyProvider继承ContentProvider类,写名字,且指定Authority(通过这个ContentResolver就可以访问到这个程序)。
Myprovider类需重写父类的6个方法。
onCreate(); // 在其他程序使用ContentResolver访问该程序数据时,Myprovider初始化,调用onCreate()方法,一般是用
于获取数据库的对象,这个数据库对象就是用来增删改查的。
public Uri insert(Uri uri, ContentValues values) {
} //在ContentResolver中调用insert()方法实际上是再调用provider中的insert方法,uri和values正是
getContentResolver.insert()方法中传过来的,可以查看源码了解,所以这里就是实现增的操作。
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
} //同insert
public int delete(Uri uri, String selection, String[] selectionArgs) {
}
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
}
public String getType(Uri uri) {
} //返回一个字符串 如果传过来的uri是以路径结尾 vnd.cursor.android.dir(id结尾 vnd.cursor.android.item)
/vnd..
内容提供器,总的来说其实不难理解,就是先是由ContentProvider给程序提供外部访问接口,指定uri的authority,并把uri访问各个表或指定某列(/#)匹配某个int值,为了后续增删改查方法中执行操作相应的表,重写各种增删改查方法(先匹配获取的uri对象,以此判断访问哪个表),用于ContentResolver的调用,然后ContentResolver通过uri的authority可以访问到这个程序的数据,执行增删改查(实际是靠调用provider的相关方法),这里uri设置访问哪个表或并指定哪列,这uri会在ContentProvider中匹配并通过switch(Urimatcher.match(uri)){case…}访问到相应表或列。
例子:
创建一个ConteProvider的子类,给一个程序提供外部访问接口
package com.example.hankzz.databaseproject;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class DatabaseProvider extends ContentProvider {
public static final int BOOK_DIR = 0;
public static final int BOOK_ITEM = 1;
public static final int CATEGORY_DIR = 2;
public static final int CATEGORY_ITEM = 3;
public static final String AUTHORITY = "com.example.hankzz.databaseproject.provider";
private static UriMatcher uriMatcher;
private MyDatabaseHelper dbHelper;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY,"book",BOOK_DIR);
uriMatcher.addURI(AUTHORITY,"book/#",BOOK_ITEM);
uriMatcher.addURI(AUTHORITY,"category",CATEGORY_DIR);
uriMatcher.addURI(AUTHORITY,"category/#",CATEGORY_ITEM);
}
public DatabaseProvider() {
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
SQLiteDatabase database = dbHelper.getWritableDatabase();
int deleterows = 0;
switch(uriMatcher.match(uri)){
case BOOK_DIR:
deleterows = database.delete("book",selection,selectionArgs);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
deleterows = database.delete("book","id=?",new String[]{bookId});
break;
case CATEGORY_DIR:
deleterows = database.delete("category",selection,selectionArgs);
break;
case CATEGORY_ITEM:
String categoryId = uri.getPathSegments().get(1);
deleterows = database.delete("category","id=?",new String[]{categoryId});
break;
}
return deleterows;
}
@Override
public String getType(Uri uri) {
// TODO: Implement this to handle requests for the MIME type of the data
// at the given URI.
switch(uriMatcher.match(uri)){
case BOOK_DIR:
return "vnd.android.cursor.dir/vnd.com.example.hankzz.databaseproject.provider.book";
case BOOK_ITEM:
return "vnd.android.cursor.item/vnd.com.example.hankzz.databaseproject.provider.book";
case CATEGORY_DIR:
return "vnd.android.cursor.dir/vnd.com.example.hankzz.databaseproject.provider.category";
case CATEGORY_ITEM:
return "vnd.android.cursor.item/vnd.com.example.hankzz.databaseproject.provider.category";
}
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO: Implement this to handle requests to insert a new row.
SQLiteDatabase database = dbHelper.getWritableDatabase();
Uri urireturn = null;
switch (uriMatcher.match(uri)){
case BOOK_DIR:
case BOOK_ITEM:
long newbookId = database.insert("book",null,values);
urireturn = Uri.parse("content://"+AUTHORITY+"/book/"+newbookId);
break;
case CATEGORY_DIR:
case CATEGORY_ITEM:
long newcategoryId = database.insert("category",null,values);
urireturn = Uri.parse("content://"+AUTHORITY+"/book/"+newcategoryId);
break;
default:
break;
}
return urireturn;
}
@Override
public boolean onCreate() {
// TODO: Implement this to initialize your content provider on startup.
dbHelper = new MyDatabaseHelper(getContext(),"bookstore.db",null,4);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO: Implement this to handle query requests from clients.
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = null;
switch (uriMatcher.match(uri)){
case BOOK_DIR:
cursor = database.query("book",projection,selection,selectionArgs,null,
null,sortOrder);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
cursor = database.query("book",projection,"id=?",new String[]{bookId},
null,null,sortOrder);
break;
case CATEGORY_DIR:
cursor = database.query("category",projection,selection,selectionArgs,null,
null,sortOrder);
break;
case CATEGORY_ITEM:
String categoryId = uri.getPathSegments().get(1);
cursor = database.query("category",projection,"id=?",new String[]{categoryId},
null,null,sortOrder);
break;
default:
break;
}
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO: Implement this to handle requests to update one or more rows.
SQLiteDatabase database = dbHelper.getWritableDatabase();
int updaterows = 0;
switch(uriMatcher.match(uri)){
case BOOK_DIR:
updaterows = database.update("book",values,selection,selectionArgs);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
updaterows = database.update("book",values,"id=?",new String[]{bookId});
break;
case CATEGORY_DIR:
updaterows = database.update("category",values,selection,selectionArgs);
break;
case CATEGORY_ITEM:
String categoryid = uri.getPathSegments().get(1);
updaterows = database.update("category",values,"id=?",new String[]{categoryid});
break;
}
return updaterows;
}
}
在另一个程序中访问该程序:
//其他代码略
insert_button = (Button) findViewById(R.id.insert_button);
insert_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("content://com.example.hankzz.databaseproject.provider/book");
ContentValues values = new ContentValues();
values.put("author","bigbrother");
values.put("name","kkb");
values.put("price",15.5);
values.put("page",20);
getContentResolver().insert(uri,values);
}
});