ContentProvider, one of the four components of Android

Posted by InternetX on Sun, 26 Jan 2020 15:59:52 +0100

Last time I talked about Activity, this time I talked about ContentProvider, one of the four components of Android

1. What is ContentProvider

ContentProvider is one of the four components of Android content provider

Function: data interaction & sharing between processes, i.e. cross process communication

2.uri introduction

1. Definition: Uniform Resource Identifier

2. Function: uniquely identify the data in the Content Provider. The external process finds the data in the corresponding Content Provider through the Uri and performs data operation

Definition format of uri

3. Briefly introduce the acquisition of the system

//Simply read inbox information

private void getMsgs() {

        Uri parse = Uri.parse("content://sms/");

        ContentResolver contentResolver = getContentResolver();

        Cursor query = contentResolver.query(parse, new String[]{"address", "date", "type", "body"}, null, null, null

        );

        if (query == null) {

            Toast.makeText(this, "I don't have an email", Toast.LENGTH_SHORT).show();

        } else {

            while (query.moveToNext()) {

                String address = query.getString(0);

                String date = query.getString(1);

                String type = query.getString(2);

                String body = query.getString(3);

                Log.d("MainActivity", "address:" + address);

                Log.d("MainActivity", "time:" + date);

                Log.d("MainActivity", "type:" + type);

                Log.d("MainActivity", "content:" + body);

                Log.d("MainActivity", "======================");

            }

            query.close();

        }

    }

//Don't forget to add permissions < uses permission Android: name = "Android. Permission. Read? SMS" / >

//Simply insert a message into your inbox

private void insertMsg() {

        ContentResolver resolver = getContentResolver();

        Uri uri = Uri.parse("content://sms/");

        ContentValues conValues = new ContentValues();

        conValues.put("address", "18888888888");

        conValues.put("type", 1);

        conValues.put("date", System.currentTimeMillis());

        conValues.put("body", "Are you Bi Niubi?");

        resolver.insert(uri, conValues);

        Log.e("HeHe", "SMS insertion completed~");

    }

//Don't forget the weight limit < uses permission Android: name = "Android. Permission. Write? SMS" / >

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

//Simple access to mobile contacts

private void getContacts(){

        //① Query the raw & contacts table to get the id of the contact

        ContentResolver resolver = getContentResolver();

        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

        //Query contact data

        Cursor cursor = resolver.query(uri, null, null, null, null);

        while(cursor.moveToNext())

        {

            //Get contact name, mobile number

            String cName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            String cNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            Log.d("MainActivity", "Full name:" + cName);

            Log.d("MainActivity", "number:" + cNum.trim());

            Log.d("MainActivity", "======================");

        }

        cursor.close();

    }

//Don't forget to add permissions to read contacts < uses permission Android: name = "Android. Permission. Read_contacts" / >

//Don't forget the < uses permission Android: name = "Android. Permission. Read" external "storage" / >

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

//Query contact information of the specified phone

  private void queryContact(String number){

        Uri uri = Uri.parse("content://com.android.contacts/data/phones/filter/" + number);

        ContentResolver resolver = getContentResolver();

        Cursor cursor = resolver.query(uri, new String[]{"display_name"}, null, null, null);

        if (cursor.moveToFirst()) {

            String name = cursor.getString(0);

            System.out.println(number + "Corresponding contact name:" + name);

        }

        cursor.close();

    }

//Add a new contact

private void AddContact() throws RemoteException, OperationApplicationException {

    //Add contacts using transactions

    Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");

    Uri dataUri =  Uri.parse("content://com.android.contacts/data");

    ContentResolver resolver = getContentResolver();

    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    ContentProviderOperation op1 = ContentProviderOperation.newInsert(uri)

            .withValue("account_name", null)

            .build();

    operations.add(op1);

    //Name, number and zip code

    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", "779878443@qq.com")

            .withValue("data2", "2")

            .build();

    operations.add(op4);

    //Add the above to your phone contacts~

    resolver.applyBatch("com.android.contacts", operations);

    Toast.makeText(getApplicationContext(), "Add success", Toast.LENGTH_SHORT).show();

}

//add permission

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

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

4. User defined ContentProvider process

public class DBOpenHelper extends SQLiteOpenHelper {

 

    final String CREATE_SQL = "CREATE TABLE test(_id INTEGER PRIMARY KEY AUTOINCREMENT,name)";

   

    public DBOpenHelper(Context context, String name, 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) {

        // TODO Auto-generated method stub

 

    }

 

}

 

Step 1: custom ContentProvider Class implementation onCreate(),getType(),Rewrite the corresponding addition, deletion, modification and query methods according to the requirements:

NameContentProvider.java

public class NameContentProvider extends ContentProvider {

 

    //Initialize some constants

     private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);       

     private DBOpenHelper dbOpenHelper;

   

    //To facilitate the direct use of UriMatcher, add URI here, and then call Matcher to match

    

     static{ 

         matcher.addURI("com.jay.example.providers.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))

        {

        //Open the database and put it in it to prove that uri matching is complete

        case 1:

            SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

            long rowId = db.insert("test", null, values);

            if(rowId > 0)

            {

                //Append ID after previous existing Uri

                Uri nameUri = ContentUris.withAppendedId(uri, rowId);

                //Notification data has changed

                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;

    }

 

}

 

Step 2: AndroidManifest.xml Medium for ContentProvider To register:

 

<!--The attributes are: fully qualified class name,For matching URI,Share data or not -->

<provider android:name="com.jay.example.bean.NameContentProvider"

            android:authorities="com.jay.example.providers.myprovider"

            android:exported="true" />

 

public class MainActivity extends Activity {

 

    private Button btninsert;

   

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

       

        btninsert = (Button) findViewById(R.id.btninsert);

       

        //Read content provider data

        final ContentResolver resolver = this.getContentResolver();

       

       

        btninsert.setOnClickListener(new OnClickListener() {

           

            @Override

            public void onClick(View v) {

                 ContentValues values = new ContentValues();

                 values.put("name", "test");

                 Uri uri = Uri.parse("content://com.jay.example.providers.myprovider/test");

                resolver.insert(uri, values);

                Toast.makeText(getApplicationContext(), "Data inserted successfully", Toast.LENGTH_SHORT).show();

               

            }

        });

}

    }

Monitor the change of ContentProvider data through ContentObserver

5. What is the relationship between ContentProvider, ContentResolver and ContentObserver?

ContentProvider: manage data, provide data addition, deletion, modification and query operations. The data source can be database, file, xml, network, etc. Content Provider provides a unified interface for these data, which can be used for inter process data sharing (Content Provider, used to provide external data)

ContentResolver: ContentResolver can operate data in different ContentProvider s with different URIs, and external processes can interact with content providers through ContentResolver (notifyChange(Uri) to send messages) (content resolver, used to obtain data provided by content providers) (ContentResolver.registerContentObserver() listens for messages)

ContentObserver: observe the change of data in ContentProvider and inform the outside (content listener, which can monitor the change of data)

Topics: Android Mobile Database xml