很多时候自己的写的service 总是会被任务管理器kill,或者有的部分手机内存太小,service 会被系统回收,就算service会自动重启,可是带来的体验总是不好!所以研究了下怎么保持service运行!
notification.flags|= Notification.FLAG_NO_CLEAR;
notification.flags=Notification.FLAG_ONGOING_EVENT;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "service", "测试防止服务被任务管理器所杀", pendingIntent);
后来一次 做自定义Notification的时候,通知栏没有显示通知,查看后发现 service 也没被kill 。所以就进一步去研究了下 最后发现 只用两行代码就能保持服务不会被kill,并且不会有通知栏通知代码如下:
查阅了很多资料发现,其实google 管方就有,ForegroundService 前台服务,让服务一直以前台任务的方式运行,可以在service 的oncreate来实现前台服务, 通过这个方法必须发送一个通知栏,让用户知道服务在运行。 Code 如下:
notification.flags|= Notification.FLAG_NO_CLEAR;
notification.flags=Notification.FLAG_ONGOING_EVENT;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "service", "测试防止服务被任务管理器所杀", pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
后来一次 做自定义Notification的时候,通知栏没有显示通知,查看后发现 service 也没被kill 。所以就进一步去研究了下 最后发现 只用两行代码就能保持服务不会被kill,并且不会有通知栏通知代码如下:
Notification notification = new Notification();
startForeground(1, notification);
这样腾讯管家能杀死。