Android Creates a Content Provider

Keywords: Android Database xml Java

Change from: http://blog.csdn.net/rankun1/article/details/51439574/(Content Provider for Content Provider and Content Resolver for Content Resolver)


brief introduction

ContentProvider Android Its function is to share data with the outside world, that is to say, you can share the data in the application to other applications through ContentProvider, and other applications can access it through ContentProvider. Add, delete, and check the data in your application. As for data sharing, we have learned the file operation mode before, and we know that data can also be shared outside by specifying the file operation mode as Context.MODE_WORLD_READABLE or Context.MODE_WORLD_WRITEABLE. So why use ContentProvider to share data? In this way, if we use file operation mode to share data, the way of accessing data will be different because of the way of data storage, which leads to the inconsistency of the way of accessing data. For example, using xml file to share data, we need xml parsing to read data; using sharedpreferences to share data, we need to use sharedpreferences to share data. API reads data.
The advantage of using ContentProvider to share data with the outside world is to unify the way of accessing data.

The principle of ContentProvider is to expose its own interface to other applications according to certain rules to access the data of its own application (in fact, it is to customize the add, delete, modify and check interface and expose it so that other applications can access their own data).

ContentResolver is to access the content provider's data according to certain rules (in fact, calling the content provider's custom interface to manipulate its data).

ContentProvider Shares Data Outside:

step

1. Define a class to inherit ContentProvider
2. Define matching rules to specify host name + path code urimatcher content:.//
3. Adding matching rules through static code blocks
4. Be sure to configure the content provider in the manifest file and don't forget to add authorities.
Explain:
The first step to inherit ContentProvider requires rewriting the following methods:
public class PersonContentProvider extends ContentProvider{
  public boolean onCreate()
  public Uri insert(Uri uri, ContentValues values)
  public int delete(Uri uri, String selection, String[] selectionArgs)
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
  public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
  public String getType(Uri uri)}

The fourth step is to configure the ContentProvider in Android Manifest. XML using <provider> so that other applications can find the ContentProvider, ContentProvider

Using authorities (host name/domain name) to uniquely identify it, you can think of ContentProvider as a website (think, the website is also a data provider), and authorities is his domain name:
<manifest .... >
   <application android:icon="@drawable/icon" android:label="@string/app_name">
       <provider android:name=".PersonContentProvider" android:authorities="cn.itcast.providers.personprovider"/>
   </application>
</manifest>


The role of the main methods of the ContentProvider class:

public boolean onCreate()
This method is called when the ContentProvider is created, and when Android is turned on, the ContentProvider is created when other applications first visit it.
public Uri insert(Uri uri, ContentValues values)
This method is used for external applications to add data to ContentProvider.
public int delete(Uri uri, String selection, String[] selectionArgs)
This method is used for external applications to delete data from ContentProvider.
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
This method is used to update data in ContentProvider for external applications.
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
This method is used for external applications to obtain data from ContentProvider.
public String getType(Uri uri)
This method is used to return the MIME type of the data represented by the current Url. If the operation data belongs to the set type, the MIME type string should begin with vnd.android.cursor.dir/.

For example, to get the Uri of all person records as content://cn.itcast.provider.person provider/person, the MIME type string returned should be: "vnd.android.cursor.dir/person". If the data to be operated on belongs to non-set type data, the MIME type string should begin with vnd.android.cursor.item/e.g. get a person record with id 10 and Uri as content://cn.itcast.provider.person provider/person/10, then the returned MIME type string should be: "vnd.android.cursor.item/person".

Uri introduction

Uri represents the data to be operated on. Uri mainly contains two parts of information: 1) ContentProvider to be operated on, 2) What data to be operated on in ContentProvider. A Uri consists of the following parts:


ContentProvider's scheme has been defined by Android, which is: content:://
The host name (or Authority) is used to uniquely identify the ContentProvider, which can be found by external callers.
path can be used to represent the data we want to operate on. path construction should be based on business, as follows:
To manipulate the record with id 10 in the person table, you can construct such a path: / person/10
To manipulate the name field of the record with id 10 in the person table, person/10/name
To manipulate all records in the person table, you can construct a path: / person
To manipulate records in XXX tables, you can construct a path: / xxx
Of course, the data to be operated on does not necessarily come from the database, but can also be stored in other ways such as files, xml or networks, as follows:
To manipulate the name node under the person node in the xml file, you can construct the path: / person/name
If you want to convert a string to Uri, you can use the parse() method in the Uri class, as follows:
Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person")

Introduction to the Use of UriMatcher Class

Because Uri represents the data to be manipulated, we often need to parse Uri and retrieve data from Uri. The Android system provides two tool classes for manipulating Uri, UriMatcher and ContentUris.

Mastering their use will facilitate our development work.
The UriMatcher class is used to match Uri, and its usage is as follows:
The first step is to register all the Uri paths you need to match, as follows:


// Constant UriMatcher.NO_MATCH denotes a return code that does not match any path
UriMatcher  sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// If the match() method matches the content://cn.itcast.provider.person provider/person path, the return matching code is 1.
sMatcher.addURI("cn.itcast.provider.personprovider", "person", 1); // Add a matching uri, if matched, the matching code will be returned.
// If the match() method matches the content://cn.itcast.provider.person provider/person/230 path, the return matching code is 2.
sMatcher.addURI("cn.itcast.provider.personprovider", "person/ 2);// is a wildcard character
switch (sMatcher.match(Uri.parse("content://cn.itcast.provider.personprovider/person/10"))) { 
  case 1
   break;
  case 2
   break;
default://mismatch
   break;
}
After registering the Uri that needs to be matched, the input Uri can be matched using the sMatcher.match(uri) method. If matched, the matching code is returned. The matching code is the third parameter passed in by calling the addURI() method.

Assuming that the matching content://cn.itcast.provider.person provider/person path is matched, the matching code returned is 1

Code example

  1. package com.itheima.transaction;  
  2.   
  3. import android.content.ContentProvider;  
  4. import android.content.ContentValues;  
  5. import android.content.UriMatcher;  
  6. import android.database.Cursor;  
  7. import android.database.sqlite.SQLiteDatabase;  
  8. import android.net.Uri;  
  9.   
  10. public class AccountProvider extends ContentProvider {  
  11.   
  12.     private static final int QUEYSUCESS = 0;  //ctrl + shift + X (capitalization) - lowercase + y  
  13.     private static final int INSERTSUCESS = 1;  
  14.       
  15.     private static final int UPDATESUCESS  = 2;  
  16.       
  17.     private static final int DELSUCESS  = 3;  
  18.       
  19.     //1. If you want to use content providers, you must define matching rules. Code: Defined matching rules. If not matched, you have a return code -1.  
  20.      static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);  
  21.   
  22.     private MyOpenHelper helper;  
  23.       
  24.     //2. I want to add matching rules  
  25.        
  26.      static{  
  27.          //Start adding matching rules  
  28.          /** 
  29.           * authority   Host name. Access my exposed data by host name. 
  30.           * path   You can also write com.itheima.contentprovider/query at will. 
  31.           * code Matching code 
  32.           */  
  33.          matcher.addURI("com.itheima.contentprovider""query", QUEYSUCESS);  
  34.          //Add Insert Matching Rules  
  35.          matcher.addURI("com.itheima.contentprovider""insert", INSERTSUCESS);  
  36.          //Add update matching rules  
  37.          matcher.addURI("com.itheima.contentprovider""update", UPDATESUCESS);  
  38.          //Add and delete matching rules  
  39.          matcher.addURI("com.itheima.contentprovider""delete", DELSUCESS);  
  40.            
  41.            
  42.      }  
  43.        
  44.       
  45.     @Override  
  46.     public boolean onCreate() {  
  47.         helper = new MyOpenHelper(getContext());  
  48.           
  49.           
  50.           
  51.         return false;  
  52.     }  
  53.   
  54.     //Uri has a larger scope. Not only can you specify tel: You can define many grammars.  
  55.     @Override  
  56.     public Cursor query(Uri uri, String[] projection, String selection,  
  57.             String[] selectionArgs, String sortOrder) {  
  58.         //Does the uri passed in match the matching rule we defined?  
  59.         int match = matcher.match(uri);  
  60.         if (match == QUEYSUCESS ) {  
  61.             //Explain the success of the match.  
  62.             SQLiteDatabase db = helper.getReadableDatabase();  //Getting database objects  
  63.             Cursor cursor = db.query("info", projection, selection, selectionArgs, nullnull, sortOrder);  
  64.               
  65.             //Note that this place does not close cursor and db  
  66.               
  67.             //With a loud roar, the database changed.  
  68.             getContext().getContentResolver().notifyChange(uri, null);  
  69.               
  70.             return cursor;  
  71.               
  72.         }else{  
  73.             //Matching failure  
  74.             throw new IllegalArgumentException("Path Matching Failure");  
  75.               
  76.         }  
  77.           
  78.           
  79.     }  
  80.   
  81.     @Override  
  82.     public String getType(Uri uri) {  
  83.         return null;  
  84.     }  
  85.   
  86.     @Override  
  87.     public Uri insert(Uri uri, ContentValues values) {  
  88.           
  89.         int match = matcher.match(uri);  
  90.         if (match == INSERTSUCESS) {  
  91.             //Explain the success of matching  
  92.             SQLiteDatabase db = helper.getReadableDatabase();  
  93.             long insert = db.insert("info"null, values);  
  94.               
  95.             //To execute the above sentence, the contents of my database have changed. First of all, I need to send a notification that I have changed.  
  96.               
  97.             if (insert>0) {  
  98.   
  99.                 //The database changes. Send a notification.  
  100.                 getContext().getContentResolver().notifyChange(uri, null);  
  101.             }  
  102.               
  103.               
  104.               
  105.               
  106.             Uri uri2 = Uri.parse("com.itheima.contentprovider/"+insert);  
  107.             return uri2;  
  108.         }else{  
  109.             //Matching failure  
  110.             throw new IllegalArgumentException("Path Matching Failure");  
  111.               
  112.         }  
  113.                   
  114.     }  
  115.   
  116.     @Override  
  117.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  118.         int match = matcher.match(uri);  
  119.         if (match == DELSUCESS) {  
  120.             //Matching success  
  121.             SQLiteDatabase db = helper.getReadableDatabase();  
  122.             int delete = db.delete("info", selection, selectionArgs);  
  123.               
  124.             if (delete>0) {  
  125.                 //With a loud roar, the database changed.  
  126.                 getContext().getContentResolver().notifyChange(uri, null);  
  127.                   
  128.             }  
  129.               
  130.               
  131.             return delete;  
  132.               
  133.         }else {  
  134.               
  135.             //Matching failure  
  136.             throw new IllegalArgumentException("Path Matching Failure");  
  137.               
  138.         }  
  139.           
  140.     }  
  141.   
  142.     @Override  
  143.     public int update(Uri uri, ContentValues values, String selection,  
  144.             String[] selectionArgs) {  
  145.           
  146.         int match = matcher.match(uri);  
  147.         if (match == UPDATESUCESS) {  
  148.             //Successful matching  
  149.             SQLiteDatabase db = helper.getReadableDatabase();  
  150.             int update = db.update("info", values, selection, selectionArgs);  
  151.               
  152.             if (update>0) {  
  153.                 //With a loud roar, the database changed.  
  154.                 getContext().getContentResolver().notifyChange(uri, null);  
  155.             }  
  156.               
  157.             return update;  
  158.         }else {  
  159.             //Matching failure  
  160.             throw new IllegalArgumentException("Path Matching Failure");  
  161.         }  
  162.           
  163.     }  
  164.   
  165. }  

ContentResolver

Use ContentResolver to call the interface provided by ContentProvider to manipulate data

When external applications need to add, delete, modify and query the data in ContentResolver, they can use the ContentResolver class to complete the task. They want to get the ContentResolver object.

You can use the getContentResolver() method provided by Activity. The ContentResolver class provides four methods for signing the same signature as the ContentProvider class:
public Uri insert(Uri uri, ContentValues values)
This method is used to add data to ContentProvider.
public int delete(Uri uri, String selection, String[] selectionArgs)
This method is used to delete data from ContentProvider.
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
This method is used to update data in ContentProvider.
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
This method is used to obtain data from ContentProvider.


The first parameter of these methods is Uri, which represents the Content Provider to be operated on and what data to operate on. Assuming that given Uri.parse("content://cn.itcast.providers.personprovider/person/10"), the Content Provider named cn.itcast.providers.personprovider will be operated on. The data to be operated on is a record of id 10 in the person table. Record.

  1. Use ContentResolver Yes ContentProvider Add, delete, modify and query the data in:  
  2.     ContentResolver resolver =  getContentResolver();  
  3.     Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person");  
  4.     //Add a record  
  5.     ContentValues values = new ContentValues();  
  6.     values.put("name""itcast");  
  7.     values.put("age"25);  
  8.     resolver.insert(uri, values);         
  9.     //Get all records in the person table  
  10.     Cursor cursor = resolver.query(uri, nullnullnull"personid desc");  
  11.     while(cursor.moveToNext()){  
  12.         Log.i("ContentTest""personid="+ cursor.getInt(0)+ ",name="+ cursor.getString(1));  
  13.     }  
  14.     //Change the name field value of the record with id 1 to liming  
  15.     ContentValues updateValues = new ContentValues();  
  16.     updateValues.put("name""liming");  
  17.     resolver.update(updateIdUri, updateValues, nullnull);  

Monitor data changes in ContentProvider

If visitors to ContentProvider need to know that the data in ContentProvider has changed, they can call when the data changes in ContentProvider.

getContentResolver().notifyChange(uri, null) notifies visitors registered on this URI, as follows:

  1. public class PersonContentProvider extends ContentProvider {  
  2.     public Uri insert(Uri uri, ContentValues values) {  
  3.         db.insert("person""personid", values);  
  4.         getContext().getContentResolver().notifyChange(uri, null);  
  5.     }  
  6.     }  
If visitors to ContentProvider need to be notified of data changes, they must use ContentObserver to listen for data (data is described by uri). When they listen for data change notifications,

The system calls the onChange() method of ContentObserver:

  1. getContentResolver().registerContentObserver(Uri.parse("content://cn.itcast.providers.personprovider/person"),  
  2.             true,//true indicates that as long as the Uri that issued the notification can be monitored at the beginning of the first parameter of the method, whether or not the side monitored URI must match the URI that issued the notification to be monitored.  
  3.                                           new PersonObserver(new Handler()));  
  4. public class PersonObserver extends ContentObserver{  
  5. public PersonObserver(Handler handler) {  
  6.     super(handler);  
  7. }  
  8. public void onChange(boolean selfChange) {  
  9.     //Corresponding business processing can be done here.  
  10. }  
  11. }  

Example code

Backup SMS with Content Analyser

  1. package com.itheima.backupsms;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8. import org.xmlpull.v1.XmlSerializer;  
  9.   
  10. import android.net.Uri;  
  11. import android.os.Bundle;  
  12. import android.os.Environment;  
  13. import android.os.FileObserver;  
  14. import android.app.Activity;  
  15. import android.database.Cursor;  
  16. import android.util.Xml;  
  17. import android.view.Menu;  
  18. import android.view.View;  
  19.   
  20. public class MainActivity extends Activity {  
  21.   
  22.     @Override  
  23.     protected void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.activity_main);  
  26.     }  
  27.   
  28.     /** 
  29.      * Click the button to back up the SMS 
  30.      *  
  31.      * @param v 
  32.      */  
  33.     public void backup(View v) {  
  34.   
  35.         try {  
  36.             //1. Initialize xml serializer  
  37.             XmlSerializer serializer = Xml.newSerializer();  
  38.             //2 Initialize xml serializer parameters  
  39.             File file = new File(Environment.getExternalStorageDirectory()  
  40.                     .getPath(), "smsbackup.xml");  
  41.             FileOutputStream fos = new FileOutputStream(file);  
  42.             serializer.setOutput(fos, "utf-8");  
  43.   
  44.             //3. Start writing xml headers  
  45.             serializer.startDocument("utf-8"true);  
  46.   
  47.             //Start writing xml root node smss  
  48.             serializer.startTag(null"smss");  
  49.             //1. To get the content of the short message database we are related to, the operation we need to do is to query the data through the content parser.  
  50.             Uri uri = Uri.parse("content://sms");  
  51.   
  52.             Cursor cursor = getContentResolver().query(uri,  
  53.                     new String[] { "address""date""body" }, nullnull,  
  54.                     null);  
  55.             while (cursor.moveToNext()) {  
  56.                 //Write sms nodes  
  57.                 serializer.startTag(null"sms");  
  58.                 String address = cursor.getString(0);  
  59.                 String date = cursor.getString(1);  
  60.                 String body = cursor.getString(2);  
  61.   
  62.                 //Start writing address nodes  
  63.                 serializer.startTag(null"address");  
  64.                 serializer.text(address);  
  65.                 serializer.endTag(null"address");  
  66.                   
  67.                 //Start writing date node  
  68.                 serializer.startTag(null"date");  
  69.                 serializer.text(date);  
  70.                 serializer.endTag(null"date");  
  71.                   
  72.                   
  73.                 //Start writing body nodes  
  74.                 serializer.startTag(null"body");  
  75.                 serializer.text(body);  
  76.                 serializer.endTag(null"body");  
  77.                   
  78.                 serializer.endTag(null"sms");  
  79.             }  
  80.   
  81.             //Start writing address date body  
  82.   
  83.             serializer.endTag(null"smss");  
  84.   
  85.             //Document closure  
  86.             serializer.endDocument();  
  87.   
  88.         } catch (Exception e) {  
  89.             e.printStackTrace();  
  90.         }  
  91.   
  92.     }  
  93.   
  94. }  

Inserting SMS with Content Parser

  1. //1. Get the content parser first.  
  2.         Uri uri = Uri.parse("content://sms");  
  3.         ContentValues values = new ContentValues();  
  4.         values.put("address""110");  
  5.         values.put("date", System.currentTimeMillis());  
  6.         values.put("body""You've done something wrong. Please come at once.");  
  7.         getContentResolver().insert(uri, values);  

Using Content Analyser to Get Contact Data

1. First, I need to query the raw_contacts table to get contact_id.
2. Get the data of mimetype data1 from the data table according to contact_id
3. Then differentiate the data types according to mimetype_id.
  1. package com.itheima.getcontactinfo.utils;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import android.content.ContentResolver;  
  7. import android.content.Context;  
  8. import android.database.Cursor;  
  9. import android.net.Uri;  
  10.   
  11. import com.itheima.getcontactinfo.domain.ContactInfo;  
  12.   
  13. public class ContactUtils {  
  14.   
  15.     public static List<ContactInfo> getContactInfos(Context context) {  
  16.   
  17.         List<ContactInfo> contactLists = new ArrayList<ContactInfo>();  
  18.         //1. First, I need to query the raw_contacts table to get the contact_id column  
  19.         //(1) How can I inquire? Using content parser path  
  20.         Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");  
  21.         Uri datauri = Uri.parse("content://com.android.contacts/data");  
  22.   
  23.         ContentResolver resolver = context.getContentResolver();  
  24.         Cursor cursor = resolver.query(uri, new String[] { "contact_id" },  
  25.                 nullnullnull);  
  26.         while (cursor.moveToNext()) {  
  27.             //Get the value of contact_id  
  28.             String contact_id = cursor.getString(0);  
  29.             System.out.println("contact_id--" + contact_id);  
  30.   
  31.             //I want to decide if contact_id is empty.  
  32.             if (contact_id != null) {  
  33.   
  34.                 ContactInfo info = new ContactInfo();  
  35.                 info.setId(contact_id);  
  36.   
  37.                 //2 To get the mimetyple_id column data1 column according to contact_id  
  38.   
  39.                 Cursor dataCursor = resolver.query(datauri, new String[] {  
  40.                         "mimetype""data1" }, "raw_contact_id=?",  
  41.                         new String[] { contact_id }, null);  
  42.                 while (dataCursor.moveToNext()) {  
  43.                     String mimetype = dataCursor.getString(0); //Get mimeytype  
  44.                     String data1 = dataCursor.getString(1);  
  45.   
  46.                     //3. Then differentiate the data types according to the mimetype type  
  47.                     if ("vnd.android.cursor.item/email_v2".equals(mimetype)) {  
  48.                         info.setEmail(data1);  
  49.   
  50.                     } else if ("vnd.android.cursor.item/name".equals(mimetype)) {  
  51.   
  52.                         info.setName(data1);  
  53.   
  54.                     } else if ("vnd.android.cursor.item/phone_v2"  
  55.                             .equals(mimetype)) {  
  56.                         System.out.println("data---Telephone number?-" + data1);  
  57.                         info.setPhone(data1);  
  58.                     }  
  59.   
  60.                 }  
  61.                 dataCursor.close();  
  62.                 contactLists.add(info); //Store info information in a collection  
  63.   
  64.             }  
  65.   
  66.         }  
  67.         cursor.close();  
  68.   
  69.         return contactLists;  
  70.   
  71.     }  
  72.   
  73. }  
  1. package com.itheima.getcontactinfo.domain;  
  2.   
  3. public class ContactInfo {  
  4.   
  5.     private String id;  
  6.     private String name;  
  7.     private String phone;  
  8.     private String email;  
  9.       
  10.       
  11.       
  12.     public String getId() {  
  13.         return id;  
  14.     }  
  15.     public void setId(String id) {  
  16.         this.id = id;  
  17.     }  
  18.     public String getName() {  
  19.         return name;  
  20.     }  
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.     public String getPhone() {  
  25.         return phone;  
  26.     }  
  27.     public void setPhone(String phone) {  
  28.         this.phone = phone;  
  29.     }  
  30.     public String getEmail() {  
  31.         return email;  
  32.     }  
  33.     public void setEmail(String email) {  
  34.         this.email = email;  
  35.     }  
  36.     @Override  
  37.     public String toString() {  
  38.         return "ContactInfo [id=" + id + ", name=" + name + ", phone=" + phone  
  39.                 + ", email=" + email + "]";  
  40.     }  
  41.   
  42.       
  43.       
  44.       
  45.       
  46. }  

Insert contacts using content parsers

1. Insert a data into raw_contacts first
2. Insert data into the data table according to mimetype contact_id
  1. package com.itheima.insert.contact;  
  2.   
  3. import android.net.Uri;  
  4. import android.os.Bundle;  
  5. import android.app.Activity;  
  6. import android.content.ContentValues;  
  7. import android.database.Cursor;  
  8. import android.view.Menu;  
  9. import android.view.View;  
  10. import android.widget.EditText;  
  11.   
  12. public class MainActivity extends Activity {  
  13.   
  14.     private EditText et_name;  
  15.     private EditText et_phone;  
  16.     private EditText et_email;  
  17.   
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.activity_main);  
  22.         //1 Find the controls we care about  
  23.           
  24.         et_name = (EditText) findViewById(R.id.et_name);  
  25.         et_phone = (EditText) findViewById(R.id.et_phone);  
  26.         et_email = (EditText) findViewById(R.id.et_email);  
  27.           
  28.           
  29.           
  30.           
  31.     }  
  32.       
  33.     /** 
  34.      * Keep contact information 
  35.      * @param v 
  36.      */  
  37.     public void click(View v){  
  38.           
  39.         //1. Get the value of edittext first.  
  40.         String name = et_name.getText().toString().trim();  
  41.         String phone = et_phone.getText().toString().trim();  
  42.         String email = et_email.getText().toString().trim();  
  43.           
  44.         //2. Insert a data into raw_contacts to get the content parser  
  45.         Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");  
  46.         Uri datauri = Uri.parse("content://com.android.contacts/data");  
  47.           
  48.         ContentValues values = new ContentValues();  
  49.         //Before inserting data, I need to query the raw_contacts table for the total number of rows of data.  
  50.         Cursor cursor = getContentResolver().query(uri, nullnullnullnull);  
  51.         int count = cursor.getCount();  //How many rows do you get?  
  52.         int contact_id =  count + 1;    
  53.           
  54.         values.put("contact_id", contact_id);  
  55.         getContentResolver().insert(uri, values);  
  56.           
  57.         //3. Insert data into the data table  
  58.           
  59.         ContentValues nameValues = new ContentValues();  
  60.         nameValues.put("data1", name);  
  61.         nameValues.put("mimetype""vnd.android.cursor.item/name");  
  62.         nameValues.put("raw_contact_id", contact_id);  
  63.         getContentResolver().insert(datauri, nameValues);  
  64.   
  65.         ContentValues phoneValues = new ContentValues();  
  66.         phoneValues.put("data1", phone);  
  67.         phoneValues.put("mimetype""vnd.android.cursor.item/phone_v2");  
  68.         phoneValues.put("raw_contact_id", contact_id);  
  69.         getContentResolver().insert(datauri, phoneValues);  
  70.           
  71.         ContentValues emailValues = new ContentValues();  
  72.         emailValues.put("data1", email);  
  73.         emailValues.put("mimetype""vnd.android.cursor.item/email_v2");  
  74.         emailValues.put("raw_contact_id", contact_id);  
  75.         getContentResolver().insert(datauri, emailValues);  
  76.           
  77.           
  78.           
  79.           
  80.           
  81.     }  
  82.   
  83.       
  84. }  

Use listeners and content parsers to listen for text messages

  1. package com.itheima.smslistener;  
  2.   
  3. import android.net.Uri;  
  4. import android.os.Bundle;  
  5. import android.os.Handler;  
  6. import android.app.Activity;  
  7. import android.database.ContentObserver;  
  8. import android.database.Cursor;  
  9. import android.view.Menu;  
  10.   
  11. public class MainActivity extends Activity {  
  12.   
  13.     private Uri uri;  
  14.     @Override  
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity_main);  
  18.           
  19.           
  20.         //1 Register a Content Observer  
  21.         uri = Uri.parse("content://sms");  
  22.         getContentResolver().registerContentObserver(uri, truenew MyObserver(new Handler()));  
  23.           
  24.     }  
  25.   
  26.       
  27.       
  28.     private  class MyObserver  extends ContentObserver{  
  29.   
  30.         public MyObserver(Handler handler) {  
  31.             super(handler);  
  32.         }  
  33.         @Override  
  34.         public void onChange(boolean selfChange) {  
  35.               
  36.             //When the database of SMS changed, I went to fetch all the contents of SMS.  
  37.               
  38.             Cursor cursor = getContentResolver().query(uri, new String[]{"address","body","date"}, nullnullnull);  
  39.             while(cursor.moveToNext()){  
  40.                   
  41.                 String address = cursor.getString(0);  
  42.                 String body = cursor.getString(1);  
  43.                 String date = cursor.getString(2);  
  44.                   
  45.                 System.out.println("address---"+address+"--body:"+body);  
  46.                   
  47.             }  
  48.               
  49.             super.onChange(selfChange);  
  50.         }  
  51.           
  52.           
  53.     }  
  54.       
  55. }  

Posted by ashebrian on Mon, 25 Mar 2019 14:00:31 -0700