黑色保活这种方式是最为简单的方法,通过系统广播什么拍照,启动,网络连接等等广播,或者其他app的广播进行唤醒。
通过启动前台Service来保持应用的一直运行。
我们看一下如何让一个service成为前台service,一般情况下我们知道service运行在后台,并且优先级也不高,当内存不够时service就会被回收掉,因此我们要想service一直保持运行,就考虑使用前台service。
前台service与普通service区别在于前台service一直有一个运行图标显示在系统通知栏。类似Notification.
public ForeService extends Service{
public void onCreate(){
super.onCreate();
//创建NOtification对象
Notification notificatin=new Notification(R.drawable.icon,"前台service",System.currentTImeMillis());
Intent intent=new Intent(this,MainActivity.class);
PendingIntent pending=PendingIntent.getActivity(this,0,intent,0);
//为通知设置布局和数据
notification.setLastestEventInfo(this,"","",pending);
//将service设置为前台service
startForeground(1,notification);
}
}
利用系统漏洞设置前台service对app进行保活,相对白色保活而言,这种方式更为隐蔽。
方式按系统分为:
API<18 : 启动前台service,直接传入一个 new Notificaation()
API>18 : 同时启动两个id相同的前台service,然后将后启动的service进行stop操作。
public class GrayService extends Service {
private final static int GRAY_SERVICE_ID = 1001;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT < 18) {
startForeground(GRAY_SERVICE_ID, new Notification());//API < 18 ,此方法能有效隐藏Notification上的图标
} else {
Intent innerIntent = new Intent(this, GrayInnerService.class);
startService(innerIntent);
startForeground(GRAY_SERVICE_ID, new Notification());
}
return super.onStartCommand(intent, flags, startId);
}
...
...
/**
* 给 API >= 18 的平台上用的灰色保活手段
*/
public static class GrayInnerService extends Service {
@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);
}
}