欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中ContentProvider和ContentResolver详解

程序员文章站 2023-11-06 20:22:58
android中contentprovider和contentresolver详解 在android中,我们的应用有的时候需要对外提供数据接口,可以有如下几种方法: 1...

android中contentprovider和contentresolver详解

在android中,我们的应用有的时候需要对外提供数据接口,可以有如下几种方法:

1)aidl 2)broadcast 3)contentprovider。

使用aidl需要我们编写aidl接口以及实现,而且对方也要有相应的接口描述,有点麻烦;使用broadcast,我们不需要任何接口描述,只要协议文档就可以了,但是有点不好就是,这种方式不直接而且是异步的;使用contentprovider我们不需要接口描述,只需要知道协议,同时这种方式是同步的,使用方便。

下面是contentprovider实现:

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 zengpeng
 * @version 1.0 create at : 2010-3-18 下午02:52:40
 */
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 method 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
    protected 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);

    // notify 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 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 parameters! 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);
    // notify any listeners and return the uri of the new row.
    getcontext().getcontentresolver().notifychange(content_uri, null);
    return newuri;
  }

  /*
   * (non-javadoc)
   * 
   * @see android.content.contentprovider#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.lang.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.content.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);

    // notify any listeners and return the updated row count.
    getcontext().getcontentresolver().notifychange(uri, null);
    return updatecount;
  }

}

配文件如下:  

 <provider android:name="testcontentprovider"
      android:authorities="test">
    </provider>

在客户端中可以使用如下方法进行调用:

 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));
        }

上面的代码是先进行插入,然后进行查询并打印。就是如此简单,所有的应用如果需要都可以对外方便的提供数据接口,同时其他应用也可以很方便的进行调用。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!