1.前台service
在onStartCommand中开启前台服务
Notification.Builder builder = new Notification.Builder(mContext);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = "foreground-service";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(id, "foreground-service", importance);
manager.createNotificationChannel(channel);//添加channel
builder = new Notification.Builder(mContext, id);
}
Notification notification = builder
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher))
.setContentTitle(mContext.getResources().getString(R.string.str_title))
.setSmallIcon(R.drawable.ic_launcher)
.setContentText(mContext.getResources().getString(R.string.str_title))
.build();
startForeground(110, notification);
在onDestroy中
stopForeground(true);
2.service重启
①START_NOT_STICKY:service被杀死,service不会重启
②START_STICKY:service被杀死,service会重启
重启后的service会走onStartCommand方法,intent为null
③START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入--------这是网上搜到的,但是我return START_REDELIVER_INTENT,kill进程,发现服务并没有重启
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
LogUtil.d(TAG, "onStartCommand intent: " + intent);
if (null != intent) {
boolean selfStartService = intent.getBooleanExtra(FLAG_SELF_START, false);
boolean selfStartServiceOneMinute = intent.getBooleanExtra(FLAG_SELF_START_ONE_MINUTE, false);
LogUtil.d(TAG, "selfStartService: " + selfStartService + ", selfStartServiceOneMinute: " + selfStartServiceOneMinute);
if (selfStartService) {
//微助手本身启动服务
if (selfStartServiceOneMinute) {//getWxUsers size=0 && 微助手不在前台
startOneMinuteJettyAndBroadcast();
return START_NOT_STICKY;//服务被杀死不会重启
}
startJettyAndBroadcast();//打开微助手 || getWxUsers size>0
LogUtil.e(TAG, "return START_STICKY---if service killed,restart");
return START_STICKY;//服务被杀死会重启
} else {
//SNIS启动的服务
RefreshIpDao.refreshIp();
if (tvIdExist()) {
getWxUsers();
} else {
LogUtil.e(TAG, "stopSelf");
stopSelf();
}
return START_NOT_STICKY;
}
}
//上面return START_STICKY时,进程被杀掉后重启,会走到这里(intent=null)
getWxUsers();
LogUtil.e(TAG, "service restart,return START_NOT_STICKY---if service killed,not restart again");
return START_NOT_STICKY;
}
最后补充下:
让service保活方法:
①return START_STICKY,service被杀 service会重启,这种方式可根据不同需求return不同的值,来实现永久保活或kill后不重启
②设置persist属性,进程被杀会重启,进程重启时可将service启动
③设置service为前台服务,这样内存不足的情况下仍然可能会将service kill