項目測試時發現的,在雙擊返回鍵關閉應用后(並未殺死后台)重新打開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