Four main components of Android Application series-use ContentProvider for cross-process communication and four major components of android

Source: Internet
Author: User

Four main components of Android Application series-use ContentProvider for cross-process communication and four major components of android

I. Problem Description

In Android, how does one implement communication between different applications (called across processes )? Android provides multiple implementation methods, this enables cross-process access to Activity, cross-process access to data of other applications through ContentProvider, Broadcast to all applications in the android system using Broadcast, and cross-process Service using AIDL. The following describes how to use ContentProvider to access data across processes and add, delete, modify, and query data.

II. Application Implementation

Use ContentProvider to share data, mainly to share the Sqlite database of the application. In another application (the metadata info in this example), provide the data source (Sqlite database) and create the ContentProvider component, the ContentProvider component provides an interface (Uri information) for data access to external applications (other applications). other applications (other in this example) use this interface (Uri information) to call cross-process methods.

:

This example involves two applications: Producer info and other.

Iii. Core of the exteninfo Application

As a data provider, the first step is to develop external accessible databases (Sqlite)

Two components are involved: DbOpenHelper and SQLiteHelper.

The Code is as follows:

Public class DbOpenHelper extends SQLiteOpenHelper {public DbOpenHelper (Context context) {super (context, "jereh. db ", null, 4) ;}@ Override public void onCreate (SQLiteDatabase db) {db.exe cSQL (" create table person (personid integer primary key "+" autoincrement, name varchar (20), phone varchar (12) null) ") ;}@ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {db.exe c SQL ("drop table person"); onCreate (db) ;}} public class SQLiteHelper {private Context context; private DbOpenHelper helper = null; public SQLiteHelper (Context context) {helper = new DbOpenHelper (context);} public void save (Person person) {// Add SQLiteDatabase db = helper. getWritableDatabase (); db.exe cSQL ("insert into person (name, phone) values (?,?) ", New Object [] {person. getName (), person. getPhone ()}); db. close ();} public void delete (int personid) {// delete SQLiteDatabase db = helper. getWritableDatabase (); db.exe cSQL ("delete from person where personid =? ", New Integer [] {personid}); db. close ();} public void update (Person person) {// change SQLiteDatabase db = helper. getWritableDatabase (); db.exe cSQL ("update person set name = ?, Phone =? Where personid =? ", New Object [] {person. getName (), person. getPhone (), person. getPersonid ()}); db. close ();} public Person find (int personid) {// query SQLiteDatabase db = helper. getReadableDatabase (); // Cursor cursor = db. rawQuery ("select * from person where personid =? ", New String [] {personid +" "}); Cursor cursor = db. rawQuery ("select * from person", null); if (cursor. moveToFirst () {int id = cursor. getInt (cursor. getColumnIndex ("personid"); String name = cursor. getString (cursor. getColumnIndex ("name"); String phone = cursor. getString (cursor. getColumnIndex ("phone"); return new Person (personid, name, phone);} cursor. close (); return null ;}}

Then write the ContentProvider component Code as follows:

Package com. jereh; public class PersonProvider extends ContentProvider {private DbOpenHelper openHelper; private static final UriMatcher MATCHER = new UriMatcher (UriMatcher. NO_MATCH); private static final int PERSONS = 1; private static final int PERSON = 2; static {MATCHER. addURI ("com. jereh. providers. personprovider "," person ", PERSONS); // * Delete the record MATCHER Based on the pesonid. addURI ("com. jereh. providers. person Provider "," person/# ", PERSON) ;}@ Override public boolean onCreate () {openHelper = new DbOpenHelper (this. getContext (); return false ;}@ Override public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder) {SQLiteDatabase sqLiteDatabase = openHelper. getReadableDatabase (); switch (MATCHER. match (uri) {case 1: return sqLiteDatabase. query ("person", Projection, selection, selectionArgs, null, null, sortOrder); case 2: long rowid = ContentUris. parseId (uri); String where = "personid =" + rowid; if (selection! = Null &&"". equals (selection. trim () {where = selection + "and" + where;} return sqLiteDatabase. query ("person", projection, where, selectionArgs, null, null, sortOrder);} return null ;}@ Override public String getType (Uri uri) {switch (MATCHER. match (uri) {case 1: return "vnd. android. cursor. dir/person "; case 2: return" vnd. android. cursor. item/person ";} return null;} @ Override public Uri insert (Uri uri, ContentValues values) {SQLiteDatabase sqLiteDatabase = openHelper. getWritableDatabase (); switch (MATCHER. match (uri) {case 1: long rowid = sqLiteDatabase. insert ("person", "name", values); return ContentUris. withAppendedId (uri, rowid); default: break;} return null;} // * delete a record of a specific personid row @ Override public int delete (Uri uri, String selection, string [] selectionArgs) {SQLiteDatabase sqLi TeDatabase = openHelper. getWritableDatabase (); switch (MATCHER. match (uri) {case 1: return sqLiteDatabase. delete ("person", selection, selectionArgs); case 2: long rowid = ContentUris. parseId (uri); String where = "personid =" + rowid; if (selection! = Null &&"". equals (selection. trim () {where = selection + "and" + where;} return sqLiteDatabase. delete ("person", where, selectionArgs);} return 0 ;}@ Override public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs) {SQLiteDatabase sqLiteDatabase = openHelper. getWritableDatabase (); switch (MATCHER. match (uri) {case 1: return sqLiteDatabase. update ("person", values, Selection, selectionArgs); case 2: long rowid = ContentUris. parseId (uri); String where = "personid =" + rowid; if (selection! = Null &&"". equals (selection. trim () {where = selection + "and" + where;} return sqLiteDatabase. update ("person", values, where, selectionArgs);} return 0 ;}}

Register provider in AndroidManifest. xml

  <provider android:name="com.jereh.PersonProvider"             android:authorities="com.jereh.providers.personprovider">

Completed the compilation of the shareinfo application.

4. Compile the other application

Next, write the other application to access the data in the Development Info. We use Android JUnit for testing. The development unit test component is as follows:

public class AccessProvider extends AndroidTestCase {    public void testInsert(){        Uri uri = Uri.parse("content://com.jereh.providers.personprovider/person");        ContentResolver resolver = this.getContext().getContentResolver();        ContentValues values = new ContentValues();        values.put("name", "xiaoli");        values.put("phone", "333333");        resolver.insert(uri, values);    }        public void testDelete(){        Uri uri = Uri.parse("content://com.jereh.providers.personprovider/person/2");        ContentResolver resolver = this.getContext().getContentResolver();        resolver.delete(uri, null, null);    }    public void testUpdate(){        Uri uri = Uri.parse("content://com.jereh.providers.personprovider/person/3");        ContentResolver resolver = this.getContext().getContentResolver();        ContentValues values = new ContentValues();        values.put("name", "ljb");        values.put("phone", "00000000");        resolver.update(uri, values, null, null);    }        public void testQuery(){        Uri uri = Uri.parse("content://com.jereh.providers.personprovider/person");        ContentResolver resolver = this.getContext().getContentResolver();        Cursor cursor = resolver.query(uri, new String[]{"name","phone"}, null, null, null);        while(cursor.moveToNext()){            String name = cursor.getString(cursor.getColumnIndex("name"));            String phone = cursor.getString(cursor.getColumnIndex("phone"));            System.out.println("name="+name+" "+"phone="+phone);        }    }}

Run the Unit Test. Test results:

 

All methods have passed the test, enabling access to data in another application (metadata info) in one application (other ).

  AndroidManifest. xml configuration:

    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.jereh.other.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />              <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <uses-library android:name="android.test.runner" />    </application>    <instrumentation    android:name="android.test.InstrumentationTestRunner"    android:targetPackage="com.jereh" android:label="My Test">    </instrumentation>

 

Author: Jerry Education
Source: http://www.cnblogs.com/jerehedu/
Copyright Disclaimer: The copyright of this article is shared by Yantai jereh Education Technology Co., Ltd. and the blog Park. You are welcome to repost it. However, you must keep this statement without the consent of the author and provide the original article connection clearly on the article page, otherwise, you are entitled to pursue legal liability.
Technical Consultation:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.