1.在看到19-24版本可以做到不可见前台serivce, 就有一个疑问 25 以后不行?
带这个疑问去看了下 源码发现,8.0可以做到不可见前台serivce,那怎么玩呢:
2.先创建个service :
public class LocalDaemonService extends Service {
private static final String TAG = "LocalDaemonService";
public static final int NOTICE_ID = 100;
@Override
public int onStartCommand(Intent intent3, int flags, int startId) {
FixForeGroundService.fixService(NOTICE_ID, TAG, this);
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
重点在 FixForeGroundService:
public class FixForeGroundService extends Service {
private static final String TAG = "FixForeGroundService";
public static String FIX_SERVICE_ACTION = "FIX_SERVICE_ACTION";
public static String FIX_SERVICE_ID = "FIX_SERVICE_ID";
public static String FIX_SERVICE_CHANNEL = "FIX_SERVICE_CHANNEL";
public static String FIX_SERVICE_DATA = "FIX_SERVICE_DATA";
public static void fixService(int notifyId, String channel, Service service) {
int sdkInt = Build.VERSION.SDK_INT;
// 这前面两个网上一大堆
if (sdkInt < Build.VERSION_CODES.JELLY_BEAN_MR2) {
service.startForeground(notifyId, new Notification());
} else if (Build.VERSION_CODES.JELLY_BEAN_MR2 <= sdkInt && Build.VERSION_CODES.N_MR1 > sdkInt) {
Notification notification = NotificationUtils.getNotification(service);
Intent intent = new Intent(service, FixForeGroundService.class);
intent.setAction(FIX_SERVICE_ACTION);
intent.putExtra(FIX_SERVICE_ID, notifyId);
intent.putExtra(FIX_SERVICE_DATA, notification);
service.startForeground(notifyId, notification);
service.startService(intent);
}else if(Build.VERSION_CODES.N_MR1 == sdkInt){
Log.d(TAG,"怎么适配25");
} else if (Build.VERSION_CODES.N_MR1 < sdkInt) {
Log.d(TAG,"进来了 sdk="+sdkInt);
Log.d(TAG,"进来了 service="+service.getClass().getCanonicalName());
//这个才是重点 先不创建通道
// NotificationUtils.createNotificationChannelForSilent(service, channel);
//创建一个没声音没震动没闪光通知 ,当然随便一个通知也行
Notification build = NotificationUtils.getNotificationWithSilent(service, channel);
service.startForeground(n