zoukankan      html  css  js  c++  java
  • 解决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

  • 相关阅读:
    转:高层游戏引擎——基于OGRE所实现的高层游戏引擎框架
    转: Orz是一个基于Ogre思想的游戏开发架构
    转:Ogre源代码浅析——脚本及其解析(一)
    IntelliJ IDEA添加过滤文件或目录
    为什么要使用ConcurrentHashMap
    volatile关键字解析
    Spring Boot MyBatis 通用Mapper 自动生成代码
    使用mysql乐观锁解决并发问题
    使用Redis分布式锁处理并发,解决超卖问题
    浅析 pagehelper 分页
  • 原文地址:https://www.cnblogs.com/Sharley/p/10248384.html
Copyright © 2011-2022 走看看