【问题标题】:How to restart service after reboot without showing any notification through forground service如何在重新启动后重新启动服务而不通过前台服务显示任何通知
【发布时间】:2020-07-29 13:41:40
【问题描述】:

背景:我有一个注册 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
    }
}

因此,如果我在MobileRestartReceiver 上使用startForegroundService,则必须使用startForeground(1,notification),这需要通知。 (注意这里你不能只启动服务它会抛出应用程序在后台的异常)

那么我怎样才能registerContentObserver 重启而不显示任何通知?

请关注:Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O

(Manifest 设置了所有权限,所以不用担心这个)

【问题讨论】:

  • 您应该使用前台服务。目前,您只是通过在onDestroy 期间不终止thread 和取消注册观察者来泄漏服务,因此在简单测试期间它可能会失败。不要查看其他应用程序(尤其是来自 google、facebook 或其他通常预装在设备上的应用程序),因为它们通常会将提升的权限嵌入到系统中,而您将无法复制它。

标签: android


【解决方案1】:

那么我如何才能在不显示任何通知的情况下从重新启动注册ContentObserver?

你不能,对不起。但请注意,您可以在 API 级别 24 及更高级别上use JobScheduler to be notified about changes in a ContentProvider

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2015-12-29
    • 2015-10-28
    相关资源
    最近更新 更多