Android四大组件之一:内容提供者相关操作

文章目录

    • 为什么需要内容提供者
    • 内容提供者原理
    • 定义内容提供者的步骤
    • 案例一:备份短信
    • 案例二:插入短信
    • 案例三:读取手机里的联系人

为什么需要内容提供者

使用内容提供者,将私有的数据库内容暴露出来

内容提供者原理

内容提供者把数据进行封装然后提供出来,其他应用都是通过内容解析者来访问

定义内容提供者的步骤

右键--新建--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 {
            //获取xml序列化实例,进行短信的备份
            XmlSerializer serializer = Xml.newSerializer();
            //设置序列化参数
            File file = new File(Environment.getExternalStorageDirectory().getPath(), "smsBackUp.xml");
            FileOutputStream fos = new FileOutputStream(file);
            serializer.setOutput(fos, "utf-8");
            //开始写xml文档的开头
            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);
                    //开始写sms节点
                    serializer.startTag(null, "sms");
                    //写address节点
                    serializer.startTag(null, "address");
                    serializer.text(address);
                    serializer.endTag(null, "address");
                    //date
                    serializer.startTag(null, "date");
                    serializer.text(date);
                    serializer.endTag(null, "date");
                    //body
                    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<>();
        // 先读取raw_contact表,读取contact_id字段,从而知道总共有几个联系人

        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);
                // 再读取data表,根据raw_contact_id读取data1列和mimetype_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:
        }
    }
}


你可能感兴趣的:(Android移动应用开发)