Sqlite Database updates triggers Service to update via Content Observer

痴心易碎 提交于 2019-12-03 08:08:24
anddev84

In general, there are two parts to handling this: you have the ContentObserver which needs to register to receive changes, as you've pointed out, and the SQLiteDatabase which has to notify the registered observers of any changes. If this is a database you own, you can create the URI that you can use to listen for.

(1) First define your URI, typically in your Database definition file.

public static final Uri CONTENT_URI = Uri.parse("mycontent://packagename/something");

(2) for your database Content Provider:

Each db function (insert, update, delete) should call through to notifyChange() after completing the operation in order to inform the observers that changes have happened.

    rowId = db.insert(tableName, null, cv);
    ...
    getContext().getContentResolver().notifyChange(newUri, null);

(3) Create and register your ContentObserver in the Service, as described in the same link you provided above (remember to override the deliverSelfNotifications() to return true)

public class MyService extends Service {
    private MyContentObserver mObserver;

    @Override
    public void onStartCommand(Intent intent, int flags, int startId) {
        ...
        mObserver = new MyContentObserver();
        getContentResolver().registerContentObserver(Dbfile.CONTENT_URI, null, mObserver);
    }

    @Override
    public void onDestroy() {
        ...
        if (mObserver != null) {
            getContentResolver().unregisterContentObserver(mObserver);
            mObserver = null;
        }
    }

    // define MyContentObserver here
}

(4) In your ContentObserver.onChange(), you can post something to the Service or handle the change right there if possible.

Also, if it helps your cause, you can customize the URI definition to handle different types of data that you are observing, register your observer for each URI, and then override ContentObserver.onChange(boolean, Uri) instead.

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!