首页 文章

然后,即使我停止了服务,Context.startForegroundService()也没有调用Service.startForeground()

提问于
浏览
7

所以我的应用程序有一些触发服务和通知的远程操作 . 在调用 startForegroundService 和服务尝试启动通知的时间之间,事情可能会发生变化,因此服务会再次检查事物的状态,然后决定要做什么 .

因此,如果我的服务决定它不需要运行,它将调用:

stopForeground(true);
stopSelf();

但由于某些原因,这似乎不起作用,因为我在进行这些调用后几乎立即得到此异常 .

11-16 13:34:23.488 15099-15099/mypackage E/AndroidRuntime: FATAL EXCEPTION: main
Process: mypackage, PID: 15099
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

那我怎么解决这个问题呢?

谢谢 .

编辑:

我创建了一个示例项目,当Activity启动时它所做的就是调用 startForegroundService 然后它在服务上执行此操作:

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"start");
        stopForeground(true);
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }

它崩溃了,无论我是否使用 stopForeground(true) .

编辑:这似乎解决了它,但似乎真的很丑,必须创建一个假通知只是为了取消它 .

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"start");
        String CHANNEL_ID = "my_channel_01";
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this, CHANNEL_ID)

                        .setContentTitle("My notification")
                        .setContentText("Hello World!");

        startForeground(-1,mBuilder.build());
        stopForeground(true);
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }

1 回答

  • 4

    我有同样的问题,我在stopSelf()之前使用相同的解决方法:

    private void fakeStartForeground() {
            NotificationCompat.Builder builder =
                    new NotificationCompat.Builder(this, CHANNEL_ID)
                            .setContentTitle("")
                            .setContentText("");
    
            startForeground(NOTIFICATION_ID, builder.build());
    }
    

    我认为有人组建谷歌应该给我们一些解决方案 . 您是否已在Google Bugs报告论坛中发帖?

相关问题