Android8.0 Not allowed to start

2019-08-15  本文已影响0人  baby_honour

原文:https://www.cnblogs.com/Sharley/p/10248384.html

参考:https://cloud.tencent.com/developer/article/1443931

在双击返回键关闭应用后(并未杀死后台)重新打开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...

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

不过不过这样的话,状态栏会有一个xxx正在运行的通知,体验不太好,如果某项任务完成后,最好主动stop掉。

总结
上一篇 下一篇

猜你喜欢

热点阅读