【监听ContentProvider中数据的变化】
如果ContentProvider的访问者需要知道ContentProvider中的数据发生变化,可以在ContentProvider 发生数据变化时调用getContentResolver().notifyChange(uri, null)来通知注册在此URI上的访问者,例子如下:
public class PersonContentProvider extends ContentProvider {
public Uri insert(Uri uri, ContentValues values) {
db.insert("person", "personid", values);
getContext().getContentResolver().notifyChange(uri, null);
}
}
如果ContentProvider的访问者需要得到数据变化通知,必须使用ContentObserver对数据(数据采用uri描述)进行监听,当监听到数据变化通知时,系统就会调用ContentObserver的onChange()方法:
getContentResolver().registerContentObserver(Uri.parse("content://cn.itcast.providers.personprovider/person"),
true,//true表示只要发出通知的Uri以方法第一个参数开头都能被监听到,否侧监听uri必须与发出通知的uri完全匹配才能被监听到
new PersonObserver(new Handler()));
public class PersonObserver extends ContentObserver{
public PersonObserver(Handler handler) {
super(handler);
}
public void onChange(boolean selfChange) {
//此处可以进行相应的业务处理
}
}
1 package cn.itcast.app; 2 3 import android.app.Activity; 4 import android.content.ContentResolver; 5 import android.content.ContentValues; 6 import android.net.Uri; 7 import android.os.Bundle; 8 import android.view.View; 9 10 public class MainActivity extends Activity { 11 /** Called when the activity is first created. */ 12 @Override 13 public void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.main); 16 } 17 18 public void insert(View v){ 19 Uri uri = Uri.parse("content://cn.itcast.providers.personprovider/person"); 20 ContentResolver resolver = this.getContentResolver(); 21 ContentValues values = new ContentValues(); 22 values.put("name", "A-App"); 23 values.put("phone", "18607687688"); 24 values.put("amount", "700000"); 25 resolver.insert(uri, values); 26 } 27 }
1 package cn.itcast.other; 2 3 import android.app.Activity; 4 import android.database.ContentObserver; 5 import android.database.Cursor; 6 import android.net.Uri; 7 import android.os.Bundle; 8 import android.os.Handler; 9 import android.util.Log; 10 11 public class MainActivity extends Activity { 12 /** Called when the activity is first created. */ 13 @Override 14 public void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.main); 17 Uri uri = Uri.parse("content://cn.itcast.providers.personprovider/person"); 18 this.getContentResolver().registerContentObserver(uri, true, new PersonContentObserver(new Handler())); 19 } 20 21 private class PersonContentObserver extends ContentObserver{ 22 23 public PersonContentObserver(Handler handler) { 24 super(handler); 25 } 26 27 @Override 28 public void onChange(boolean selfChange) { 29 // select * from person order by personid desc limit 1 30 Uri uri = Uri.parse("content://cn.itcast.providers.personprovider/person"); 31 Cursor cursor = getContentResolver().query(uri, null, null, null, "personid desc limit 1"); 32 if(cursor.moveToFirst()){ 33 String name = cursor.getString(cursor.getColumnIndex("name")); 34 Log.i("MainActivity", name); 35 } 36 } 37 38 } 39 }