Context.startForegroundService() did not then call

2019-01-04 06:46发布

I am using Service Class on the Android O OS.

I plan to use the Service in the background.

The Android recommendation states that startService should use startForegroundService.

If you use startForegroundService, the Service throws a Context.startForegroundService() did not then call Service.startForeground() error.

What's wrong with this?

20条回答
做个烂人
2楼-- · 2019-01-04 07:37

Just a heads up as I wasted way too many hours on this. I kept getting this exception even though I was calling startForeground(..) as the first thing in onCreate(..). In the end I found that the problem was caused by using NOTIFICATION_ID = 0. Using any other value seems to fix this.

查看更多
仙女界的扛把子
3楼-- · 2019-01-04 07:38

I have researched on this for a couple of days and got the solution. Now in Android O you can set the background limitation as below

The service which is calling a service class

Intent serviceIntent = new Intent(SettingActivity.this,DetectedService.class);
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){

                        SettingActivity.this.startForegroundService(serviceIntent);
                    }else{
                        startService(serviceIntent);
                    }

and the service class should be like

public class DetectedService extends Service { 
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        int NOTIFICATION_ID = (int) (System.currentTimeMillis()%10000);
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(NOTIFICATION_ID, new Notification.Builder(this).build());
        }


        // Do whatever you want to do here
    }
}
查看更多
登录 后发表回答