奥利奥(Oreo)上的前台服务异常

时间:2018-06-27 13:22:58

标签: java android

我在上下文中调用了startForegroundService而不是startService

final Intent intent = new Intent(this, LocationService.class);
 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      startForegroundService(intent);
  }else {
      startService(intent);
  }

它在LocationService中调用了onStartCommand:

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String CHANNEL_ID = "channel_01";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "Channel of Location",
                    NotificationManager.IMPORTANCE_DEFAULT);
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("")
                    .setContentText("")
                    .setAutoCancel(true)
                    .build();
            startForeground(1, notification);
        } else {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setContentTitle("")
                    .setContentText("")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);

            Notification notification = builder.build();

            startForeground(1, notification);
        }
        return START_NOT_STICKY;
    }

我有这样的错误:

  

致命异常:android.app.RemoteServiceException:   然后没有调用Context.startForegroundService()   Service.startForeground()          在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:2101)          在android.os.Handler.dispatchMessage(Handler.java:108)          在android.os.Looper.loop(Looper.java:166)          在android.app.ActivityThread.main(ActivityThread.java:7425)          在java.lang.reflect.Method.invoke(Method.java)          在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:245)          在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

0 个答案:

没有答案