概况
定义:contentProvider是android中提供专门进行不同程序数据共享的方式,其底层实现是Binder,contentProvider以表格的形式组织数据,而且包含多个表。
作用:访问系统预置的ContentProvider,如通讯录,自定义contentProvider暴露给外界,方便调用。
ContentProvider的工作过程
首先给一张大图(反应了ContentProvider的工作流程)
简单介绍:
- 一个应用启动入口方法是ActivityThread的main方法,main方法中会创建ActivityThread的实例和主线程的消息队列,然后通过attch方法远程调用远程的Ams的attachApplication,并把ApplicationThread对象给Ams。ams的attachApplication方法会调用ApplicationThread的bindApplication,经过handler传回ActivityThread中处理,即交给handleBindApplication方法,此方法会创建Application对象,和加载ContentProvider。
- 所以Application的onCreate的执行在加载ContentProvider之后。
- ApplicationThread是Binder对象,它的Binder接口是IApplicationThread,主要用于Ams和ActivityThread的之间通信。
聊聊之后发生的事:
- contentProvider开始后,外界无法直接访问,必须通过AMS根据uri获取对应的ContentProvider的binder接口(IcontentProvider),来访问数据。
- 通过android:multiprocess设置ContentProvider是单实例还是多实例。
- 访问ContentProvider通过ContentResolver,实际上就是ApplicationContentProvider,第一次触发ContentProvider方法,伴随着启动其所在进程。
选query方法,来仔细介绍:(具体参见开发艺术探索)
1、首先获取IContentProvider对象,(通过acquireProvider方法获取ContentProvider)。
2、发送一个进程间请求给AMS让其启动目标ContentProvider,最后通过installProvider修改引用次数。
3、AMS首先启动进程,然后启动ContentProvider,具体启动进程的方法是startProcessLocked方法,内部通过Process的start方法完成进程的启动。
4、ActivityThread的attach方法会将Application对象通过AMS的attachApplication方法跨进程传递给AMS,最终会完成ContentProvider创建过程。
5、一个流程:
attachApplication(ams)--》 attachApplicationLocked(ams)--》 bindApplication(ApplicationThread) -(发送消息)-》Handler--》handleBindApplication
6、四个步骤:
- 创建ContextImpl和Instrumentation
- 创建Application对象
- 启动当前进程的ContentProvider并调用其OnCreate
- 调用Application的onCreate方法
上例子
首先是读取系统的一些信息:
package com.example.contentprovider;
import android.Manifest;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
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.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private TextView text_content;
private Button change_text;
private Button intent_second;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
//初始化
private void init(){
//三组权限
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
//没有授权,则申请授权
//ActivityCompat.requestPermissions() 参数一:context 参数二:申请的权限名数组 参数三:请求码,要求唯一值
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, 2);
} else {
getContacts();
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_CONTACTS}, 2);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_SMS}, 1);
} else {
getMsgs();
}
// insertMsg();
initView();
}
//初始化页面和设置点击事件
private void initView(){
text_content = (TextView)findViewById(R.id.text_content);
change_text = (Button)findViewById(R.id.add_contacts);
intent_second = (Button)findViewById(R.id.intent_to_second);
intent_second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
});
change_text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
//添加联系人,因为原方法抛出了异常,所以调用的时候需要try-catch语句
AddContact();
}catch (Exception e){
e.printStackTrace();
}
}
});
}
//查询短信一些信息
private void getMsgs(){
//短信的uri
Uri uri = Uri.parse("content://sms/");
ContentResolver resolver = getContentResolver();
//获取的是哪些列的信息
Cursor cursor = resolver.query(uri, new String[]{"address","date","type","body"}, null, null, null);
while(cursor.moveToNext())
{
String address = cursor.getString(0);
String date = cursor.getString(1);
String type = cursor.getString(2);
String body = cursor.getString(3);
System.out.println("地址:" + address);
System.out.println("时间:" + date);
System.out.println("类型:" + type);
System.out.println("内容:" + body);
System.out.println("======================");
}
cursor.close();
}
//添加联系人
private void AddContact() throws RemoteException,OperationApplicationException{
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
ContentResolver resolver = getContentResolver();
ArrayList operations = new ArrayList<>();
ContentProviderOperation op1 = ContentProviderOperation.newInsert(uri)
.withValue("account_name",null)
.build();
operations.add(op1);
ContentProviderOperation op2 = ContentProviderOperation.newInsert(dataUri)
.withValueBackReference("raw_contact_id",0)
.withValue("mimetype","vnd.android.cursor.item/name")
.withValue("data2","Coder_pig")
.build();
operations.add(op2);
ContentProviderOperation op3 = ContentProviderOperation.newInsert(dataUri)
.withValueBackReference("raw_contact_id", 0)
.withValue("mimetype", "vnd.android.cursor.item/phone_v2")
.withValue("data1", "13798988888")
.withValue("data2", "2")
.build();
operations.add(op3);
ContentProviderOperation op4 = ContentProviderOperation.newInsert(dataUri)
.withValueBackReference("raw_contact_id", 0)
.withValue("mimetype", "vnd.android.cursor.item/email_v2")
.withValue("data1", "[email protected]")
.withValue("data2", "2")
.build();
operations.add(op4);
//将上述内容添加到手机联系人中~
resolver.applyBatch("com.android.contacts", operations);
Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
}
//获取联系人信息
private void getContacts(){
ContentResolver resolver = getContentResolver();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursor = resolver.query(uri,null,null,null,null);
while (cursor.moveToNext()){
String cName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String cNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.print("姓名:"+cName);
System.out.println("号码:"+cNum);
System.out.println("++++++++++++++++++++++");
}
cursor.close();
}
//动态权限申请
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
} else {
Toast.makeText(MainActivity.this, "read sms denied", Toast.LENGTH_SHORT).show();
}
break;
case 2:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getMsgs();
} else {
Toast.makeText(MainActivity.this, "read call denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
运行结果:
然后是自定义ContentProvider
目录结构:
DBOpenHelper是关于数据库的一个类:
package com.example.contentprovider.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBOpenHelper extends SQLiteOpenHelper {
final String CREATE_SQL = "CREATE TABLE test(_id INTEGER PRIMARY KEY AUTOINCREMENT,name)";
public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context,name,null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
内容提供器:(ContentProvider)
package com.example.contentprovider.util;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class NameContentProvider extends ContentProvider {
//初始化一些常量
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private DBOpenHelper dbOpenHelper;
static {
matcher.addURI("com.example.contentprovider.myprovider","test",1);
}
@Override
public boolean onCreate() {
//实例化对象
dbOpenHelper = new DBOpenHelper(this.getContext(),"test.db",null,1);
return true;
}
@Override
public Cursor query( Uri uri,String[] projection,String selection, String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri , ContentValues values) {
switch (matcher.match(uri)){
//证明uri是否匹配成功
case 1:
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
long rowId = db.insert("test",null,values);
if(rowId > 0){
// 在前面已有的uri后面追加id
Uri nameUri = ContentUris.withAppendedId(uri,rowId);
//通知内容提供器,内容发生改变了
getContext().getContentResolver().notifyChange(nameUri,null);;
return nameUri;
}
}
return null;
}
@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;
}
}
AsyncTask(用于更新ui)
package com.example.contentprovider.util;
import android.os.AsyncTask;
import android.widget.TextView;
public class MyAsyncTask extends AsyncTask {
private TextView txt;
private String str;
public MyAsyncTask(TextView txt,String str){
super();
this.txt = txt;
this.str = str;
}
@Override
protected String doInBackground(Integer... integers) {
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
txt.setText(str);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
SecondActivity:
package com.example.contentprovider;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.contentprovider.util.DBOpenHelper;
import com.example.contentprovider.util.MyAsyncTask;
public class SecondActivity extends AppCompatActivity {
private DBOpenHelper dbOpenHelper;
private String name = null;
private TextView text_show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
text_show = (TextView)findViewById(R.id.txt_show_data);
}
public void onClick(View view){
if(view.getId() == R.id.cursor_data){
watch();
}
}
private void watch(){
dbOpenHelper = new DBOpenHelper(this,"test.db",null,1);
SQLiteDatabase sqLiteDatabase = dbOpenHelper.getReadableDatabase();
Cursor cursor = sqLiteDatabase.query("test",new String[]{"name"},"name=?",new String[] { "测试" },null,null,null);
while (cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex("name"));
//输出查询结果
System.out.println("查询到的数据是:\n"+"name: "+name);
}
if(name != null){
MyAsyncTask myAsyncTask = new MyAsyncTask(text_show,name);
myAsyncTask.execute();
}
//关闭数据库
sqLiteDatabase.close();
}
}
在其他程序的调用:(ProviderTeminate的MainActivity)
package com.example.providerterminate;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btninsert;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btninsert = (Button) findViewById(R.id.btn_insert);
//读取contentprovider 数据
final ContentResolver resolver = this.getContentResolver();
btninsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put("name", "测试");
Uri uri = Uri.parse("content://com.example.contentprovider.myprovider/test");
resolver.insert(uri, values);
Toast.makeText(getApplicationContext(), "数据插入成功", Toast.LENGTH_SHORT).show();
}
});
}
}