标签:des android style class blog code
当程序A在执行insert、update、delete时,通过getContext().getContentResolver().notifyChange(uri, observer)方法来告诉所有注册在该Uri的监听者数据发生改变
参数1uri:注册的uri
参数2observer:注册的监听者
/** * 插入操作 */ @Override public Uri insert(Uri uri, ContentValues values) { if (uriMatcher.match(uri) != USERSCODE) { throw new IllegalArgumentException("unknow URI" + uri); } SQLiteDatabase db = dh.getReadableDatabase(); long rowId = db.insert("users", "username", values); //监听数据变化,通知注册在uri上的监听者 //参数1:注册的uri,参数2:监听者 getContext().getContentResolver().notifyChange(uri, null); return ContentUris.withAppendedId(uri, rowId); }
在B程序通过registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer)方法来监听A程序的数据改变
package com.example.android_providers; import android.app.Activity; import android.content.ContentResolver; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.widget.SimpleCursorAdapter; import android.view.View; import android.widget.ListView; import android.widget.TextView; public class CopyOfMainActivity extends Activity { private ListView lv_users; private TextView tv_tip; private SimpleCursorAdapter adapter; private ContentResolver contentResolver; private static final String URL = "content://www.csdn.com.provider.userContentProvider/users"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv_users = (ListView) findViewById(R.id.lv_users); tv_tip = (TextView) findViewById(R.id.tv_tip); // 获取内容解析器对象 contentResolver = getContentResolver(); initDate(); // 注册监听器 getContentResolver().registerContentObserver(Uri.parse(URL), true, new UserContentObserver(handler)); } /* * 初始化数据 */ private void initDate() { // 执行查询 Cursor c = contentResolver.query(Uri.parse(URL), new String[] { "userid as _id", "username", "userphone" }, null, null, "userid desc"); // 控制层 adapter = new SimpleCursorAdapter(this, R.layout.item_phone, c, new String[] { "username", "userphone" }, new int[] { R.id.tv_name, R.id.tv_phone }, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); lv_users.setAdapter(adapter); } class UserContentObserver extends ContentObserver { private Handler handler; public UserContentObserver(Handler handler) { super(handler); this.handler = handler; } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); tv_tip.setVisibility(View.VISIBLE); tv_tip.setText("有新的信息,请点击加载"); } } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; }
实例应用:
http://blog.csdn.net/zhaoyazhi2129/article/details/30064965
赵雅智_ProviderContent监听数据变化,布布扣,bubuko.com
标签:des android style class blog code
原文地址:http://blog.csdn.net/zhaoyazhi2129/article/details/30062783