Android 8.0 不再允许后台service直接通过startService方式去启动,否则就会引起IllegalStateException。一般的解决方式:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context,TestService.class));
} else {
context.startService(new Intent(context,TestService.class));
}
然后必须在TestService中调用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);
}
}
|