startForegroundService()在应用程序BOOT_COMPLETED上的Oreo中引发IllegalStateException [英] startForegroundService() is throwing IllegalStateException in Oreo on app BOOT_COMPLETED

查看:140
本文介绍了startForegroundService()在应用程序BOOT_COMPLETED上的Oreo中引发IllegalStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The application I am having (in Android O) will start a service after device reboot. Once the device is rebooted, in the onReceive() method of the broadcast receiver it is calling the service as startForegroundService() for Android OS 8 and above.

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

在服务类内部,它是通过onStartCommand()方法启动通知的.

Inside the service class it is starting the notification from the onStartCommand() method.

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

But still it is throwing the IllegalStateException. Did someone faced similar issues in Android OS 8 and above?

推荐答案

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

You have to call startForeground() from the started service, it's in the docs:

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

Once the service has been created, the service must call its startForeground() method within five seconds.

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

So for example you need to do this from your Service class:

@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());
    }
} 

这篇关于startForegroundService()在应用程序BOOT_COMPLETED上的Oreo中引发IllegalStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆