如何在不打开应用程序的情况下使ContentObserver工作? [英] How to make ContentObserver work without having application opened?
问题描述
我需要让我的应用程序侦听Android中通讯录中的更改。我已经读到可以使用 ContentObserver
并监听 ContactsContract.Contacts
中的更改来完成。似乎当应用程序关闭时ContentObserver的生命周期就结束了。
I need to have my application listen for changes in addressbook in Android. I have read that it can be done using ContentObserver
and listening for changes in ContactsContract.Contacts
. It seems the lifecycle of the ContentObserver ends when the application is closed.
即使未打开应用程序,如何使ContentObserver正常工作?
How do I make the ContentObserver work even if the application wasn't opened?
推荐答案
在OnStartCommand中用返回START_STICKY;
来注册内容观察者在onCreate中注册它。
register your Content Observer in the OnStartCommand with return START_STICKY;
instead of registering it in the onCreate. It works for me.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
getContentResolver().registerContentObserver(uri,true, new SMSObserver(new Handler(), getBaseContext()));
return START_STICKY;
}
这篇关于如何在不打开应用程序的情况下使ContentObserver工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!