简述:
contentprovider:是安卓四大组件之一,是实现应用程序间数据共享最标准的方式。
若A提供数据给B,则A写contentprovider,B写resolver将数据释放出来。
本次实验将自建一个provider,然后在另一个app中使用resolver调用这个provider。
1.写resolver的app
主要代码
package com.example.appp1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public Button button;
private static final String AUTHORITY="lxy.Provider1";
private static final Uri NOTIFY_URI=Uri.parse("content://"+AUTHORITY+"/person");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button);
ContentResolver resolver=getContentResolver();
Uri uri=Uri.parse("content://lxy.provider2/student");
ContentValues values=new ContentValues();
values.put("id",1);
values.put("name","lxy");
values.put("age","20");
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
resolver.insert(uri,values);
}
});
}
}
界面
2.写provider的APP
主要代码
package com.example.provider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class MyDAO {
//操作数据对象的method方法
private Context context;
private SQLiteDatabase datebase;
public MyDAO(Context context){
this.context=context;
MyDBhelper dBhelper=new MyDBhelper(context,"lxy",null,1);
datebase=dBhelper.getWritableDatabase();
}
public Uri lxyInsert(ContentValues contentValues
){
ContentValues values1 = new ContentValues();
Uri uri=Uri.parse("content://lxy.provider2/student");
Uri inserturi;
long rowId=datebase.insert("student",null,values1);
inserturi= ContentUris.withAppendedId(uri,rowId) ;
context.getContentResolver().notifyChange(inserturi,null);
return inserturi;
}
}
同时打开两个app,点击第一个app的button按钮,观察到app2新增加一条datebase记录
仓库地址