1、启动Service
public static void startService(Context context) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
context.startForegroundService(new Intent(context, InterceptSercice.class));
} else {
context.startService(new Intent(context, InterceptSercice.class));
}
}
2、把Service之前台(必须要设置)
Utils.startForeground(this);
此方法要放在onCreate 或onStartCommand【建议后者】
注
public static void startForeground(Service service) {
if (Build.VERSION.SDK_INT >= 26) {
if (createNotificationChannelServicesPass(service, Env.CHANNEL_ID_SERVICE)) {
return;
}
Notification notification = new NotificationCompat.Builder(service.getApplicationContext(), Env.CHANNEL_ID_SERVICE)
.build();
// id cannot 0
service.startForeground(-1, notification);
}
}
private static boolean createNotificationChannelServicesPass(Service service, String channelId) {
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(channelId,
service.getResources().getString(R.string.notification_channel_service),
NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = ((NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE));
if (manager == null) {
LogUtil.e(TAG, "createNotificationChannel fail");
return true;
}
// channel.setLockscreenVisibility();
manager.createNotificationChannel(channel);
}
return false;
}