【问题标题】:startForegroundService() is throwing IllegalStateException in Oreo on app BOOT_COMPLETEDstartForegroundService() 在应用程序 BOOT_COMPLETED 上的 Oreo 中抛出 IllegalStateException
【发布时间】:2018-11-21 22:44:22
【问题描述】:

我拥有的应用程序(在 Android O 中)将在设备重启后启动服务。设备重新启动后,在广播接收器的 onReceive() 方法中,它将调用服务作为 Android OS 8 及更高版本的 startForegroundService()。

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    context.startForegroundService(intent);
} else {
    context.startService(intent);
}

在服务类内部,它从 onStartCommand() 方法开始通知。

但它仍然抛出 IllegalStateException。有人在 Android OS 8 及更高版本中遇到过类似问题吗?

【问题讨论】:

  • IllegalStateException 与哪个消息?

标签: android service illegalstateexception foreground-service


【解决方案1】:

您必须从已启动的服务中调用startForeground(),它在文档中:

服务创建后,服务必须在五秒内调用其 startForeground() 方法。

Source

因此,例如,您需要在 Service 类中执行此操作:

@Override
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String CHANNEL_ID = "channel_01";
        String CHANNEL_NAME = "Channel Name";

        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        channel.setSound(null, null);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);

        Builder notification = new Builder(this, CHANNEL_ID).setSound(null).setVibrate(new long[]{0});
        notification.setChannelId(CHANNEL_ID);

        startForeground(1, notification.build());
    }
} 

【讨论】:

    【解决方案2】:

    系统允许应用在后台调用 Context.startForegroundService()。但是,应用必须在服务创建后的 5 秒内调用该服务的 startForeground() 方法。

    如下所示编写您的服务的 onCreate。

    @Override
     public void onCreate() {
        super.onCreate();
    
        if (Build.VERSION.SDK_INT >= 26) {
            String CHANNEL_ID = "my_channel_01";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
    
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
    
            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("")
                    .setContentText("").build();
    
            startForeground(1, notification);
        }
     }
    

    这样 startForeground() 可以在服务启动后 5 秒内被调用。

    【讨论】:

      猜你喜欢
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 2019-06-10
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多