In Android, our applications sometimes need to provide external data interfaces. The following methods can be used: 1) aidl 2) broadcast 3) contentprovider.
To use aidl, We need to write and implement the aidl interface, and the other party must have the corresponding interface description, which is a bit of a hassle. To use broadcast, we don't need any interface description, as long as the Protocol documentation is enough, however, this method is not direct and asynchronous. Using contentprovider, we do not need to describe the interface, but only need to know the Protocol. At the same time, this method is synchronous and easy to use. The following is the contentprovider implementation:
Package COM. backgroundservice; import android. content. contentprovider; import android. content. contentvalues; import android. content. urimatcher; import android. database. cursor; import android. database. SQLite. sqlitedatabase; import android. database. SQLite. sqlitequerybuilder; import android.net. uri; import android. util. log;/***** todo ** @ author tianlu * @ version 1.0 create at: 01:58:39 */Public Class testcontentprovider extends contentprovider {private sqlitedatabase MDB; private databasehelper mdbhelper = NULL; Private Static final string database_name = "rssitems. DB "; Private Static final string database_table_name =" rssitems "; Private Static final int db_version = 1; Private Static final int all_messages = 1; Private Static final int specific_message = 2; // set up our URL matchers To help us determine what an // incoming URI parameter is. private Static final urimatcher uri_matcher; static {uri_matcher = new urimatcher (urimatcher. no_match); uri_matcher.adduri ("test", "item", all_messages); uri_matcher.adduri ("test", "item/#", specific_message );} // here's the public URI used to query for RSS items. public static final URI content_uri = Uri. parse ("content: // test/item ");/ /Here are our column name constants, used to query for field values. public static final string id = "_ id"; public static final string name = "name"; public static final string value = "value "; public static final string default_sort_order = ID + "DESC"; Private Static class databasehelper extends abstractdatabasehelper {@ override protected string [] createdbtables () {// todo auto-generated met Hod stub string SQL = "CREATE TABLE" + database_table_name + "(" + ID + "integer primary key autoincrement," + name + "text," + value + "text ); "; return New String [] {SQL };}@ override protected string [] dropdbtables () {// todo auto-generated method stub return NULL ;} @ override protected string getdatabasename () {// todo auto-generated method stub return database_name;} @ override protec Ted int getdatabaseversion () {// todo auto-generated method stub return db_version;} @ override protected string gettag () {// todo auto-generated method stub return testcontentprovider. class. getsimplename () ;}/ *****/Public testcontentprovider () {// todo auto-generated constructor stub}/** (non-javadoc) ** @ see android. content. contentprovider # Delete (android.net. uri, * Java. lang. string, Java. Lang. String []) */@ override public int Delete (URI Uri, string selection, string [] selectionargs) {// note argument checking Code omitted. Check your parameters! Int rowcount = MDB. delete (database_table_name, selection, selectionargs); // returns y any listeners and return the deleted row count. getcontext (). getcontentresolver (). notifychange (Uri, null); Return rowcount;}/** (non-javadoc) ** @ see android. content. contentprovider # GetType (android.net. uri) */@ override Public String GetType (URI) {Switch (uri_matcher.match (URI) {Case all_messages: Return "Vnd. android. cursor. DIR/rssitem "; // list of items. case specific_message: Return "Vnd. android. cursor. item/rssitem "; // specific item. default: return NULL;}/** (non-javadoc) ** @ see android. content. contentprovider # insert (android.net. uri, * android. content. contentvalues) */@ override public URI insert (URI Uri, contentvalues values) {// note argument checking Code omitted. check your parame Ters! Check that // your row addition request succeeded! Long rowid =-1; rowid = MDB. insert (database_table_name, name, values); Uri newuri = Uri. withappendedpath (content_uri, "" + rowid); log. I ("testcontentprovider", "saved a record" + rowid + "" + newuri); // returns y any listeners and return the URI of the new row. getcontext (). getcontentresolver (). policychange (content_uri, null); Return newuri;}/** (non-javadoc) ** @ see android. content. contentprov Ider # oncreate () */@ override public Boolean oncreate () {// todo auto-generated method stub try {mdbhelper = new databasehelper (); mdbhelper. open (getcontext (); MDB = mdbhelper. getmdb ();} catch (exception e) {e. printstacktrace ();} return true;}/** (non-javadoc) ** @ see android. content. contentprovider # query (android.net. uri, * Java. lang. string [], Java. lang. string, Java. lang. string [], * Java. lan G. string) */Public cursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder) {// we won't bother checking the validity of Params here, but you should! // Sqlitequerybuilder is the helper class that creates the // proper SQL syntax for us. sqlitequerybuilder qbuilder = new sqlitequerybuilder (); // set the table we're querying. qbuilder. settables (database_table_name); // If the query ends in a specific record number, we're // being asked for a specific record, so set the // where clause in our query. if (uri_matcher.match (URI) = specific_message) {Qbuilder. appendwhere ("_ id =" + Uri. getlastpathsegment (); log. I ("testcontentprovider", "_ id =" + Uri. getlastpathsegment ();} // make the query. cursor c = qbuilder. query (mdb, projection, selection, selectionargs, null, null, sortorder); log. I ("testcontentprovider", "get records"); C. setnotificationuri (getcontext (). getcontentresolver (), Uri); Return C;}/** (non-javadoc) ** @ see android. conten T. contentprovider # Update (android.net. uri, * android. content. contentvalues, Java. lang. string, Java. lang. string []) * // @ override public int Update (URI Uri, contentvalues values, string selection, string [] selectionargs) {// note argument checking Code omitted. check your parameters! Int updatecount = MDB. update (database_table_name, values, selection, selectionargs); // returns y any listeners and return the updated row count. getcontext (). getcontentresolver (). notifychange (Uri, null); Return updatecount ;}}
The configuration file is as follows:
<provider android:name="TestContentProvider" android:authorities="test"></provider>
You can use the following method to call a client:
ContentValues values = new ContentValues(); values.put(TestContentProvider.NAME, "testname1"); values.put(TestContentProvider.VALUE, "testvalu1e"); Uri newAddUri = TestActivity.this.getContentResolver().insert(TestContentProvider.CONTENT_URI, values); Cursor c = TestActivity.this.managedQuery(newAddUri, new String[]{TestContentProvider.NAME}, null, null, null); Log.i("TestActivity", "" + c.getCount()); if(c.moveToNext()) { Log.i("TestActivity", c.getString(0)); }
The above code is inserted first, then queried and printed. It is so simple that all applications can provide data interfaces conveniently if needed, and other applications can also conveniently call the interfaces.