服务中注册的 ContentObserver 在应用程序终止时被终止

ContentObserver registered in service is killed when app killed

我需要能够检测联系人数据何时发生更改(对地址簿中任何联系人的任何类型的更改)。

我正在使用这个 ContentObserver:

public class ContactsContentObserver extends ContentObserver {
private Context context;
private Handler toastMessageHandler;

public ContactsContentObserver(Handler handler, Context ctx) {
    super(handler);
    context = ctx;
}

@Override
public void onChange(boolean selfChange) {
    this.onChange(selfChange,null);
}

@Override
public void onChange(boolean selfChange, Uri uri) {
    // Change Detected! Do something.
}

}

我在这样的服务中注册了这个观察者:

 @Override
public int onStartCommand (Intent intent, int flags, int startId){
    super.onStartCommand(intent, flags, startId);
    registerContactsContentObserver();
    return START_STICKY;
}

private void registerContactsContentObserver(){
    ContactsContentObserver myObserver = new ContactsContentObserver(new Handler(), this);
    getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, myObserver);
}

我在主 activity 中启动此服务。

只要 activity 打开(即使在后台),它就可以正常工作,并且每次更改任何联系人数据时都会调用 onChange() 方法。

但是如果我在android

中通过从recent apps中清除它来手动关闭应用程序,它根本不起作用

我是不是做错了什么?服务不是应该 运行 即使应用程序已关闭吗?

我已经在 pskink

的帮助下解决了这个问题

像这样在前台启动服务:

private void runAsForeground(){
    Intent notificationIntent = new Intent(this, LauncherActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
            notificationIntent, PendingIntent.FLAG_ONE_SHOT);

    Notification notification=new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("test")
            .setContentIntent(pendingIntent).build();

    startForeground(1, notification);

}

@Override
public int onStartCommand (Intent intent, int flags, int startId){
    super.onStartCommand(intent, flags, startId);
    runAsForeground();              
    registerContactsContentObserver();
    return START_STICKY;
}

问题已解决。

尽管如此,我仍然不明白为什么首先会出现这个问题,因为该服务是粘性的,即使应用程序关闭也应该 运行。即使android为了节省内存停止了服务,也应该重新启动它。

有人可以向我解释为什么在前台启动服务与在后台启动常规粘性服务有什么不同吗?