本文摘自微信公衆號“android高心星的私塾”
一 聲明
二 保活手段
1 業界保活手段:黑色保活,灰色保活,白色保活
2 黑色保活:
3 白色保活:
4 灰色保活
代碼這樣寫:
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
/**
* APP灰色保活
* Created by fflin on 2016/4/23.
*/
public class GrayService extends Service {
private final static int GRAY_SERVICE_ID = 1001;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//API < 18,此方法能有效地隱藏notification的圖標
if (Build.VERSION.SDK_INT < 18) {
startForeground(GRAY_SERVICE_ID, new Notification());
} else {
Intent intent1 = new Intent(this, GrayInnerService.class);
startService(intent1);
startForeground(GRAY_SERVICE_ID, new Notification());
}
return super.onStartCommand(intent, flags, startId);
}
//給API >= 18 的平臺上做灰色保護手段
public class GrayInnerService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(GRAY_SERVICE_ID, new Notification());
stopForeground(true);
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
}
}