android 前置service

来源:互联网 发布:福建金税三期软件下载 编辑:程序博客网 时间:2024/06/06 01:28

在android开发中,如何写一个不被干掉的service一直是一个大问题。
尤其是现在这么多一键加速的app,分分钟让你的服务被干掉。

总结一下,从2.x版本一路走来,大家也研究了很多保护service不被干掉的方法:
1. 最基本的,不要用bindService去开启一个服务,而是用startService,因为前者会将activity与service绑定到一起,当你的activity挂掉时,service也会挂掉,而大家都知道,当你的activity在后台运行时,是非常容易被系统释放掉的。
2. 其次,你可以在onStartCommand方法中,返回START_STICKY,其实这并不能保证服务不被干掉,它只是表示该服务被干掉后会自动重启。但是这并不是一个特别好的办法,因为你是无法控制重启的时间的
3. 设置android:process为独立进程。
4. 开启一个前置服务:
这个详细说一下。其实是你先开启了一个服务,然后把这个服务给设置成前置的,对应的,要声明一个Notification在推送栏里,我想这是android防止大家都偷偷摸摸的开前置服务吧:

//开启一个前置服务                Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.app_name),                        System.currentTimeMillis());                Intent notificationIntent = new Intent(context, MainActivity.class);                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);                notification.setLatestEventInfo(context, getText(R.string.action_settings),                        getText(R.string.definition_High), pendingIntent);                startForeground(1, notification);

需要注意一点,startForeground(1, notification); 的第一个参数如果是0,那不会在推送栏显示Notification

1 0
原创粉丝点击