4.4.1 A Preliminary Exploration of ContentProvider
Category Android Basic Tutorial
Introduction to This Section:
>
This section introduces the last of the four major components in Android—ContentProvider (Content Provider). Some readers may wonder, "Aren't there five major components in Android, including Intent?" Yes, Intent is also very important, but it is just the link between these components! Let's talk about this ContentProvider. When would we use it? There are the following two scenarios:
1. We want to access other applications in our own application, or some data exposed to us by some ContentProviders, such as phone contacts, text messages, etc.! If we want to read or modify these data, we will need to use ContentProvider!
2. Our own application wants to expose some of its data to other applications for reading or operation. We can also use ContentProvider. In addition, we can choose the data to be exposed, thus avoiding the leakage of our private data!
It seems very powerful, but it is actually very simple to use. Let's learn about ContentProvider below. Official Documentation: ContentProvider In this section, we will explain the concept of ContentProvider, write a few commonly used examples of using system ContentProvider, and customize ContentProvider!
1. Explanation of the Concept of ContentProvider:
2. Using the ContentProvider Provided by the System
>
In fact, many times we use ContentProvider not to expose our own data, but more often to read information from other applications through ContentResolver. The most commonly used is to read system APP information, contacts, multimedia information, etc.! If you want to call these ContentProviders, you need to consult the relevant API documentation yourself! In addition, different versions may correspond to different URLs! Here's how to get the URL and the corresponding database table fields, taking the most commonly used contacts as an example, and others can be searched on Google~ raw_contact table, data table, mimetypes table!
1) Simple Reading of Inbox Information:
Core Code:
private void getMsgs(){
Uri uri = Uri.parse("content://sms/");
ContentResolver resolver = getContentResolver();
//What columns of information are obtained
Cursor cursor = resolver.query(uri, new String[]{"address","date","type","body"}, null, null, null);
while(cursor.moveToNext())
{
String address = cursor.getString(0);
String date = cursor.getString(1);
String type = cursor.getString(2);
String body = cursor.getString(3);
System.out.println("Address:" + address);
System.out.println("Time:" + date);
System.out.println("Type:" + type);
System.out.println("Content:" + body);
System.out.println("======================");
}
cursor.close();
}
Don't forget to add the permission to read the inbox in AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_SMS"/>
Running Results:
Some running results are as follows:
2) Simply Insert a Message into the Inbox
Core Code:
private void insertMsg() {
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://sms/");
ContentValues conValues = new ContentValues();
conValues.put("address", "123456789");
conValues.put("type", 1);
conValues.put("date", System.currentTimeMillis());
conValues.put("body", "no zuo no die why you try!");
resolver.insert(uri, conValues);
Log.e("HeHe", "SMS insertion completed~");
}
Running Results:
Note:
The above code can implement the function of writing SMS below 4.4, but it cannot be written on 5.0. The reason is: Starting from 5.0, software other than the default SMS application cannot send SMS messages in the form of writing to the SMS database!
3) Simple Reading of Mobile Phone Contacts
Core Code:
private void getContacts(){
//①Query the raw_contacts table to get the contact's ID
ContentResolver resolver = getContentResolver();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
//Query contact data
cursor = resolver.query(uri, null, null, null, null);
while(cursor.moveToNext())
{
//Get the contact name, mobile number
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 content to the phone contacts~
resolver.applyBatch("com.android.contacts", operations);
Toast.makeText(getApplicationContext(), "Added successfully", Toast.LENGTH_SHORT).show();
}
**Running result:**
**Don't forget permissions:**
<uses-permission android:name="android.permission.WRITE_CONTACTS"/> <uses-permission android:name="android.permission.WRITE_PROFILE"/>
---
## 3. Custom ContentProvider
>
We rarely define our own ContentProvider because we often do not want our application's data to be exposed to
other applications. Although this is the case, learning how to use ContentProvider is still necessary. Having one more way to transfer data, right?
Next, we will implement it step by step:
Before we start, we need to create a database creation class (the database content will be discussed later~):
**DBOpenHelper.java**
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, implement onCreate(), getType(), and override the corresponding add, delete, update, 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;
//For easy direct use of UriMatcher, addURI here, and then call Matcher for matching below
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))
{
//Put the database opening inside to prove that URI matching is complete
case 1:
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
long rowId = db.insert("test", null, values);
if(rowId > 0)
{
//Append the ID to the existing Uri in front
Uri nameUri = ContentUris.withAppendedId(uri, rowId);
//Notify that the 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**: Register the ContentProvider in AndroidManifest.xml:
<!--Attributes in order: fully qualified class name, URI for matching, whether to share data --> <provider android:name="com.jay.example.bean.NameContentProvider" android:authorities="com.jay.example.providers.myprovider" android:exported="true" />
Okay, the part of the ContentProvider is completed!
---
Next, create a new project, and let's implement the part of ContentResolver. We will insert a piece of data directly by clicking a button:
**MainActivity.java**
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 data from contentprovider
final ContentResolver resolver = this.getContentResolver();
btninsert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
1.5.1 Git Tutorial on Basic Operations of Local Repositories
1.8 Project Related Analysis (Various Files, Resource Access)
2.5.4 AutoCompleteTextView (Auto-Complete Text Box) Basic Usage
[2.5.6 ViewFlipper (Flip View) Basic Usage](android-tutorial
5.2.4 Fragment Instance Detailed Lecture - Bottom Navigation Bar + ViewPager Page Switching
6.2 Data Storage and Access - SharedPreferences to Save User Preference Parameters
6.3.1 Data Storage and Access - An Introduction to SQLite Database
6.3.2 Data Storage and Access - Another Look at SQLite Database
7.1.1 Android Network Programming Essentials and Http Protocol Learning
8.3.4 Paint API - Detailed Explanation of Xfermode and PorterDuff (I)
8.3.5 Paint API - Detailed Explanation of Xfermode and PorterDuff (II)
8.3.6 Paint API - Detailed Explanation of Xfermode and PorterDuff (III)
8.3.7 Paint API - Detailed Explanation of Xfermode and PorterDuff (IV)
8.3.8 Paint API - Detailed Explanation of Xfermode and PorterDuff (V)
[8.3.10 Paint API - ColorFilter
12.4 DrySister's Girl Viewing App (First Edition) - 4. Adding Data Caching (Integrate SQLite)