文章目录
- 为什么需要内容提供者
- 内容提供者原理
- 定义内容提供者的步骤
- 案例一:备份短信
- 案例二:插入短信
- 案例三:读取手机里的联系人
为什么需要内容提供者
使用内容提供者,将私有的数据库内容暴露出来
内容提供者原理
内容提供者把数据进行封装然后提供出来,其他应用都是通过内容解析者来访问
定义内容提供者的步骤
右键--新建--other--contentprovider
然后输入类名,和唯一标识URI(一般为所在包名)
写一个静态代码,添加匹配规则
在静态代码里定义匹配项,并在指定的方法中实现
其他应用可以通过内容的解析者访问数据
案例一:备份短信
package com.dsl.backupsms;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.xmlpull.v1.XmlSerializer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button click = findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.READ_SMS)!= PackageManager.PERMISSION_GRANTED&&ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.READ_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
back_up();
}
}
});
}
@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) {
back_up();
} else {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
@SuppressWarnings("all")
private void back_up() {
try {
XmlSerializer serializer = Xml.newSerializer();
File file = new File(Environment.getExternalStorageDirectory().getPath(), "smsBackUp.xml");
FileOutputStream fos = new FileOutputStream(file);
serializer.setOutput(fos, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "smss");
Uri uri = Uri.parse("content://sms/");
Cursor cursor = getContentResolver().query(uri, new String[]{"address", "date", "body"}, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String address = cursor.getString(0);
String date = cursor.getString(1);
String body = cursor.getString(2);
serializer.startTag(null, "sms");
serializer.startTag(null, "address");
serializer.text(address);
serializer.endTag(null, "address");
serializer.startTag(null, "date");
serializer.text(date);
serializer.endTag(null, "date");
serializer.startTag(null, "body");
serializer.text(body);
serializer.endTag(null, "body");
serializer.endTag(null, "sms");
}
}
serializer.endTag(null, "smss");
serializer.endDocument();
} catch (Exception e) {
e.printStackTrace();
}
}
}
案例二:插入短信
package com.dsl.smsinsertdata;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button click = findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.SEND_SMS}, 1);
} else {
send();
}
}
});
}
@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) {
send();
} else {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
public void send(){
String address = "1234";
String body = "赵四";
long l = System.currentTimeMillis();
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> message = smsManager.divideMessage(body);
smsManager.sendMultipartTextMessage(address, null, message, null, null);
Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_LONG).show();
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://sms/inbox");
ContentValues values = new ContentValues();
values.put("address", address);
values.put("body", body);
values.put("type", 1);
values.put("date", l);
contentResolver.insert(uri, values);
}
}
案例三:读取手机里的联系人
package com.dsl.readContacter;
public class Contact {
private String id;
private String name;
private String email;
private String phone;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Contact{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
package com.dsl.readContacter;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
public class ReadContactsUtils {
public static List<Contact> readContact(Context context){
List<Contact> list = new ArrayList<>();
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
Cursor cursor = context.getContentResolver().query(uri, new String[]{"contact_id"}, null, null, null);
while (cursor.moveToNext()) {
String contact_id = cursor.getString(0);
Contact contact = new Contact();
if (contact_id!=null){
contact.setId(contact_id);
Cursor dataCursor = context.getContentResolver().query(dataUri, new String[]{"data1", "mimetype"}, "raw_contact_id=?", new String[]{contact_id}, null, null);
while (dataCursor.moveToNext()) {
String data1 = dataCursor.getString(0);
String mimetype = dataCursor.getString(1);
if ("vnd.android.cursor.item/name".equals(mimetype)){
contact.setName(data1);
}else if("vnd.android.cursor.item/phone_v2".equals(mimetype)){
contact.setPhone(data1);
}else if("vnd.android.cursor.item/email_v2".equals(mimetype)){
contact.setEmail(data1);
}
}
}
list.add(contact);
}
return list;
}
}
package com.dsl.readContacter;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import java.net.URI;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.READ_CONTACTS}, 1);
} else {
List<Contact> list = ReadContactsUtils.readContact(getApplicationContext());
for (Contact contact:list){
System.out.println("contact:"+contact);
}
}
}
@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) {
List<Contact> list = ReadContactsUtils.readContact(getApplicationContext());
for (Contact contact:list){
System.out.println("contact:"+contact);
}
} else {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
}