如何让service 不会被第三方任务管理器kill

来源:互联网 发布:php yii 编辑:程序博客网 时间:2024/04/19 08:13
很多时候自己的写的service 总是会被任务管理器kill,或者有的部分手机内存太小,service 会被系统回收,就算service会自动重启,可是带来的体验总是不好!所以研究了下怎么保持service运行!

   查阅了很多资料发现,其实google 管方就有,ForegroundService 前台服务,让服务一直以前台任务的方式运行,可以在service 的oncreate来实现前台服务, 通过这个方法必须发送一个通知栏,让用户知道服务在运行。 Code 如下:


Notification notification = new Notification(R.drawable.icon, "服务开启", System.currentTimeMillis());
        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);


这样就能保持service 运行,可是通知栏不能清除 ,一清除就会被kill。
后来一次 做自定义Notification的时候,通知栏没有显示通知,查看后发现 service 也没被kill 。所以就进一步去研究了下 最后发现 只用两行代码就能保持服务不会被kill,并且不会有通知栏通知代码如下:

Notification notification = new Notification();

startForeground(1, notification);

这样腾讯管家能杀死。

1 0
原创粉丝点击