Android 关于8.0的Service问题(Not allowed to start service Intent)

Android 8.0 不再允许后台service直接通过startService方式去启动,否则就会引起IllegalStateException

8.0要做出如下修改

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    Intent intent = new Intent(getApplicationContext(), TimerService.class);
    startForegroundService(intent);
} else {
    Intent intent = new Intent(getApplicationContext(), TimerService.class);
     startService(intent);
}

在Service的onCreate函数内

public static final String CHANNEL_ID_STRING = "service_01";

NotificationManager notificationManager = (NotificationManager) MyApplication.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);

}

 

使用这种方法启动的service,在状态栏里面会出现一个xxx正在运行的标志。

 

奇怪的是,小米的10.0的手机没有这个bug,目前只在华为HuaWei/EMOTION发现这个bug,不晓得什么情况

你可能感兴趣的:(不用找系列,android)