(Android) ContentProvider 实例

ContentProvider 用于应用程序(Android Application)之间传递数据,包括Insert, update, delete, query。

下面的例子是在两个应用之间传递数据。

 

应用一(创建ContentProviderTestA)

TestContentProvider.java

public class TestContentProvider extends ContentProvider {

 private final static UriMatcher URI_MATCHER;
 private final static int ALL_MESSAGES = 1;
 private final static int SPECIFIC_MESSAGE = 2;

 static {
  URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
  URI_MATCHER.addURI("com.example.contentprovidertesta", "item", ALL_MESSAGES);
  URI_MATCHER.addURI("com.example.contentprovidertesta", "specialitem", SPECIFIC_MESSAGE);
 }

 public static final Uri CONTENT_URI = Uri
   .parse("content://com.example.contentprovidertesta");

 private final static String DEBUG = "ContentProvider";

 @Override
 public String getType(Uri uri) {
  switch (URI_MATCHER.match(uri)) {
  case SPECIFIC_MESSAGE:
   Log.d(DEBUG, "specialitem");
   return "specialitem";
  case ALL_MESSAGES:
   Log.d(DEBUG, "item");
   return "item/normal";
  }
  return "item";
 }

 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs) {
  Log.d(DEBUG, uri.toString());
  if (getType(uri).equals("specialitem")) {
   Log.d(DEBUG, "-----------delete sepcial items-------------");
  } else {
   Log.d(DEBUG, "-----------delete-------------");
  }
  return 0;
 }

 @Override
 public Uri insert(Uri uri, ContentValues values) {
  return null;
 }

 @Override
 public boolean onCreate() {
  return false;
 }

 @Override
 public Cursor query(Uri uri, String[] projection, String selection,
   String[] selectionArgs, String sortOrder) {
  return null;
 }

 @Override
 public int update(Uri uri, ContentValues values, String selection,
   String[] selectionArgs) {
  return 0;
 }
}

AndroidManifest.xml

<application>

<provider
            android:name="com.example.contentprovidertesta.TestContentProvider"
            android:authorities="com.example.contentprovidertesta" />

</application>

 

应用二 ContentProviderTest

public class MainActivity extends Activity {

 private final Uri testallmessage = Uri
   .parse("content://com.example.contentprovidertesta/item");
 private final Uri testspecialmessage = Uri
   .parse("content://com.example.contentprovidertesta/specialitem");

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 }

 @Override
 protected void onResume() {
  super.onResume();
  testContentProvider();
 }

 private void testContentProvider() {
  getContentResolver().delete(testallmessage, null, null);
  getContentResolver().delete(testspecialmessage, null, null);
 }

}

 

当安装两个应用后,再运行应用二出现的log,

content://com.example.contentprovidertesta/item
item
-----------delete-------------
content://com.example.contentprovidertesta/specialitem
specialitem
-----------delete sepcial items-------------

 

 

 

posted on 2013-08-12 19:23  you Richer  阅读(428)  评论(0编辑  收藏  举报