因为APP有一个模块是要记录巡查轨迹(在下一篇文章中介绍),需要在后台持续记录GPS数据,考虑到耗电因素,最好是能在熄屏状态下运行,而熄屏状态下APP又有可能被系统Kill掉,所以,采取将Service设置前台服务,并播放无声音乐,同时引导用户设置白名单的方式,确保巡查轨迹记录完整。
先介绍以下用到的三种保活技术:
一、设置前台服务。 代码如下:
private String CHANNEL_ONE_ID = "TraceNotification_1001";
private NotificationCompat.Builder builder;
private NotificationManager manager;
/**
* 开启通知栏
*/
private void initNotification() {
//获取管理器
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//创建notification
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ONE_ID)
.setSmallIcon(R.mipmap.loctionicon) // 设置状态栏内的小图标
.setContentTitle("记录轨迹")
.setContentText("当前位置:") // 设置内容
.setWhen(System.currentTimeMillis())// 设置该通知发生的时间
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)// 锁屏显示全部通知
.setCategory(Notification.CATEGORY_SERVICE)//设置类别
.setPriority(NotificationCompat.PRIORITY_MAX);// 优先级为:重要通知
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//安卓8.0以上系统要求通知设置Channel,否则会报错
//IMPORTANCE_NONE 关闭通知
//IMPORTANCE_MIN 开启通知,不会弹出,但没有提示音,状态栏中无显示
//IMPORTANCE_LOW 开启通知,不会弹出,不发出提示音,状态栏中显示
//IMPORTANCE_DEFAULT 开启通知,不会弹出,发出提示音,状态栏中显示
//IMPORTANCE_HIGH 开启通知,会弹出,发出提示音,状态栏中显示
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, "服务常驻通知", NotificationManager.IMPORTANCE_LOW);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);//锁屏显示全部通知
manager.createNotificationChannel(notificationChannel);
builder.setChannelId(CHANNEL_