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

  • 相关阅读:
    AS2介绍
    .net 资源大收藏
    智能客户端(SmartClient)(转载)
    [WPF Bug清单]之(3)——暗中创建文件的打开文件对话框
    实例分析SharpDevelop代码完成功能
    [WPF Bug清单](序)与之(1)——可以多选的单选ListBox
    实例分析SharpDevelop代码完成功能(续)——添加对Boo语言的支持
    [WPF Bug清单]之(2)——RadioButton的IsChecked绑定失效
    让WPF窗体程序支持命令行方式运行的三种方式
    基于文法分析的表达式计算器的实现
  • 原文地址:https://www.cnblogs.com/Sharley/p/10248384.html
Copyright © 2011-2022 走看看