Day 10 + 11 ContentProvider content provider


1, Introduction to ContentProvider:

1.ContentProvider content provider (one of the four components) is mainly used to realize the function of data sharing between different applications.
2. Skill points:
(1) Access the content provider of the system (***********)
Mobile phone contact / audio / video / gallery / SMS/
(2) Write your own content provider
3. Note:

2, Schematic diagram

3, Get the music in the phone and display it in ListView

1. Read / write SD card permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

2. Code implementation

(1) Entity class

(2) Tool class acquisition

public class SongsUtils {
    //Returns the full name of the local song
    public static List<SongBean> getSongs(Context context){
        ArrayList<SongBean> songBeans = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        if(cursor != null ){
            while (cursor.moveToNext()){
                String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String album_id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                //Get album cover according to album id
                Cursor query = contentResolver.query(Uri.parse("content://media/external/audio/albums/" + album_id), null, null, null, null);
                if(query != null){
                    while (query.moveToNext()){
                        String album = query.getString(query.getColumnIndex("album_art"));
                        songBeans.add(new SongBean(name,singer,data,album));
                    query.close();//Close cursor

            cursor.close();//Close cursor
        return songBeans;

4, Get mobile phone contacts and display them in ListView

1. Add permission to obtain mobile phone contact

<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>

2. Add permission to obtain mobile phone contact

 //Get mobile contacts
    public void click1(View view) {
        //TODO 1: get ContentResolver
        ContentResolver resolver = getContentResolver();
        //TODO 2: determine the uri and the field to query
        Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] strs={ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER};
        //TODO 3: execute the query and display the result traversal in the ListView and store it in the local database
        Cursor cursor=resolver.query(uri,strs,null,null,null);
        ArrayList<Phone> list=new ArrayList<>();
            String name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            list.add(new Phone(name,number));
            //Store each record in its own database
        //Display the data in the list collection in the ListView, which is omitted here
    class Phone{
        private String name;
        private String number;

        public Phone(String name, String number) {
   = name;
            this.number = number;

        public String getName() {
            return name;

        public void setName(String name) {
   = name;

        public String getNumber() {
            return number;

        public void setNumber(String number) {
            this.number = number;

5, Get SMS

(1) Add permission to get SMS

 <uses-permission android:name="android.permission.READ_SMS" />

(2) Get the SMS content, display it in the ListView, and store the information in the database
uri: Telephony.Sms.CONTENT_URI
Field: telephone.sms.address address content of telephone.sms.body

//Get SMS
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void click2(View view) {
        ContentResolver resolver = getContentResolver();
        Uri uri= Telephony.Sms.CONTENT_URI;
        String[] strs={Telephony.Sms.BODY,Telephony.Sms.ADDRESS};
        Cursor cursor=resolver.query(uri,strs,null,null,null);
        //The first type is ListView, and the second type is save to database
        ArrayList<Msm> list=new ArrayList<>();
            String address=cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));
            String body=cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));
            list.add(new Msm(address,body));
            //Execute insert statement

    class Msm{
        private String address;
        private String body;

        public Msm(String address, String body) {
            this.address = address;
            this.body = body;

        public String getAddress() {
            return address;

        public void setAddress(String address) {
            this.address = address;

        public String getBody() {
            return body;

        public void setBody(String body) {
            this.body = body;

4, Get all the pictures / videos of your phone

5, Get phone call records

. . . .

B: Custom content provider

1, What is a custom content provider

When it comes to content providers, you should think of providers and requestors. Before, we obtained mobile phone contacts. The provider is the system APP itself and the requester is us; Now, if we want to be a provider and let others access our database, we need to customize the content provider.

2, Idea:

1. Provider: ContentProvider
(1) Create a database, and the custom class inherits SQLiteOpenHelper
(2) Customize the content provider class, inherit the ContentProvider, override the insert/delete/update/query method, and provide methods to the outside world
(3) Registering content providers in manifest files
2. Requester: ContentResolver
(1) Obtain the ContentResolver object through the getContentResolver method of Context
(2) Determine uri
(3) Call the insert/delete/update/query method to access the database

3, Provider code: creating my_contentprovider moudle

(1) Custom classes inherit SQLiteOpenHelper

public class MyHelper extends SQLiteOpenHelper {
    public MyHelper(Context context) {
        super(context, "user.db", null, 1);

    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table user (_id integer primary key autoincrement ,name varchar(30),age integer)");
        for(int i=1;i<10;i++){
            db.execSQL("insert into user values(null,?,?)",new String[]{"Total finalization"+i+"",i+""});

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


(2) Custom content provider class, inheriting ContentProvider

public class MyProvider extends ContentProvider {
    private MyHelper myHelper;
    private SQLiteDatabase db;
    //Get database
    public boolean onCreate() {
        myHelper=new MyHelper(getContext());
            return false;
            return true;

    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        return  db.query("user",projection,selection,selectionArgs,null,null,sortOrder);

    public String getType(@NonNull Uri uri) {
        return null;

    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        return uri;

    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        return db.delete("user",selection,selectionArgs);

    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return db.update("user",values,selection,selectionArgs);

(3) Registering content providers in manifest files

 <!--Registered content provider exported Can it be accessed by other applications   authorities: uri  name: Full path of class-->

Note: the authorities attribute in the manifest file is the uri of the requestor: com.bawei

4, Content requestor code

(1) Get ContentResolver directly

Determine Uri: conten://com.bawei You must add content://

public class MainActivity extends AppCompatActivity {
    private ContentResolver contentResolver;
    private Uri uri;

    protected void onCreate(Bundle savedInstanceState) {
    //user (_id integer primary key autoincrement ,name varchar(30),age integer)
    public void query(){
        //Parameter 1: uri parameter 2: query field parameter 3: condition parameter 4: Yes? Assignment parameter 5: sorting
        Cursor cursor=contentResolver.query(uri,new String[]{"_id","name"},null,null,null);
    public  void delete(){
        //Parameter 1: uri parameter 2: condition parameter 3: Yes? assignment
        int raw=contentResolver.delete(uri,"name=?",new String[]{"Sweet snow"});
    public void insert(){
        //Add data
        ContentValues contentValues=new ContentValues();
        contentValues.put("name","Sweet snow");

C. Use the content provider to dynamically obtain the verification code

D. Custom permissions

1. Usage scenario?

Defining permissions is generally used for exposed components to improve security. Android allows one application (client) to call the components of another application (server). Then, as a server application, the corresponding components must be exposed before the client application can access them. Of course, permission is not necessary when exposing. If the exposed component does not have permission, any other application can call the component; If the component has applied for permission, only the application with the permission can call the component.

2. How?

(1) Content provider's manifest document

User defined permissions + permissions used when content providers register

<!--1.Custom permissions-->
<!--2.Set custom permissions when registering content-->

Explain the following attributes:

  • Name, which is the name of the permission.
  • description, which is the introduction of permissions.
  • permissionGroup, which specifies the group of the permission.
  • protectionLevel, which specifies the protection level. normal is generally used

Android divides permissions into several protection levels, such as normal, dangerous, signature, etc. Normal is the normal permission, which does not pose a risk to the privacy of users or devices; Dangerous permission is dangerous permission, which usually brings risks to the privacy of users' data or devices; Signature means that only applications with the same signature can use this permission.

(2) Add permission to content resolver manifest file

<uses-permission android:name="com.bawei.permission.WRITE"></uses-permission>
<uses-permission android:name="com.bawei.permission.READ"></uses-permission>

Tags: Android

Posted on Thu, 21 Oct 2021 00:36:15 -0400 by sparq