Android 白名单保活
最近有遇到保活的需求,一开始想到的就是之前的黑科技保活比如像素Activity,播放无声MP3,双进程等方法,但是随着Android系统的更新,这些非常规的方法或多或少都已经失效了。作为研发虽然很不乐意做这种功能,但是产品是不是提一句,没办法只有硬着头皮做了。接下来就是愉快的码代码。
1.方法一常驻通知栏
对于部分APP来说,常驻通知栏就能达到基本保活的需求,其实就是在APP启动的时候创建一Service,重写onStartCommand并返回1将应用设置为前台应用;当然通知栏还要适配一下Android O
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("Demo","应用包名"+"demo", NotificationManager.IMPORTANCE_LOW);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
startForeground(1,getNotification());
return START_STICKY;
}
private Notification getNotification() {
Intent contentIntent = new Intent();
contentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
contentIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
contentIntent.setData(Uri.fromParts("package", "应用包名", null));
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.logo_icon_xiaowo)
.setContentIntent(PendingIntent.getActivity(this, 0, contentIntent, 0))
.setContentTitle("\""+"应用包名"+"\"正在运行")
.setContentText("触摸即可了解详情或停止应用");
//设置Notification的ChannelID,否则不能正常显示