背景:我有一个注册ContentObserver的服务。即使应用未打开或设备重启,也应设置ContentObserver。只有后台服务才能实现。
问题:好像Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
不能仅仅启动backgroundService。它只能提供前台服务,但前台服务需要通知。效果不好,因为用户会看到通知。 (Facebook不会在重新启动时显示任何通知,但仍会注册其服务)
(可以在这里找到完整的代码:http://www.digitstory.com/android-detect-new-contact-addition/,其中有我为什么使用Handler的更多描述) 我的服务是:-
public class ContactWatchService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
try {
//Register contact observer <--- I register here
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onCreate() {
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
现在重新启动BoradCastReceiver:-
public class MobileRestartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, ContactWatchService.class)); //TODO--> ERROR won't work as app is in background
}
}
因此,如果我在startForegroundService
上使用MobileRestartReceiver
,则必须做startForeground(1,notification)
,这需要通知。 (请注意,您不能仅启动服务,否则会引发应用程序在后台运行的异常)
那么如何在重启后registerContentObserver
而不显示任何通知?
请注意:Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
。
(清单设置了所有权限,所以不用担心)
答案 0 :(得分:0)
那么如何在不显示任何通知的情况下从重新启动状态注册ContentObserver?
不能,抱歉。不过请注意,您可以use JobScheduler
to be notified about changes in a ContentProvider
使用API级别24和更高版本。