首页 > 解决方案 > 奥利奥前台服务异常

问题描述

我在上下文中调用了 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() 没有在 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)

标签: javaandroid

解决方案


推荐阅读