初始化的Service异常处理
在Application中,我们经常会做一些初始化的操作,而且会把这些初始化的操作放到一个service里面去做。
问题就出在Android 8.0 不再允许后台service直接通过startService方式去启动,否则就会引起IllegalStateException。
解决方法
1.在你的Service里面,做启动方式判断,然后再onCreat方法里做兼容
Intent intent = new Intent(context, InitService.class);
intent.setAction("com.mycp.initservice");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
@Override
public void onCreate() {
super.onCreate();
//适配8.0service
NotificationManager notificationManager = (NotificationManager) ExampleApp.app().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mChannel = new NotificationChannel("InitService", getString(R.string.app_name),
NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(mChannel);
Notification notification = new Notification.Builder(getApplicationContext(), "InitService").build();
startForeground(1, notification);
}
}