解决Android8.0之后开启service时报错IllegalStateException: Not allowed to start service Intent ...

项目测试时发现的,在双击返回键关闭应用后(并未杀死后台)重新打开APP,其他手机都OK,但是8.0的手机会出现较频繁的crash。检查代码,问题锁定在重新开启应用时的startService()上。

查找资料说是Android 8.0 不再允许后台service直接通过startService方式去启动,否则就会引起IllegalStateException。而网上给出的解决方式大多是这样的:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, MyService.class));
    } else {
        context.startService(new Intent(context, MyService.class));
    }

然后必须在Myservice中调用startForeground():

@Override
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}

 

不过可能是我代码本身的问题,使用上面代码之后应用报出RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid ch...

然后做了一些修改,其他的不变,只是在要开启的service中给notification添加 channelId:

public static final String CHANNEL_ID_STRING = "service_01";

    @Override
    public void onCreate() {
        super.onCreate();
        //适配8.0service
        NotificationManager notificationManager = (NotificationManager) MyApp.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID_STRING, getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(mChannel);
            Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
            startForeground(1, notification);
        }
}

ok,可以正常跑起来了。

 

参考地址:https://blog.csdn.net/o279642707/article/details/82352431?utm_source=blogxgwz0

 

posted @ 2019-01-10 10:25  Sharley  阅读(8986)  评论(1编辑  收藏  举报