Android进程保活方法
2016-04-18 18:28
489 查看
Android进程保活方法
当前进程保活分为三种方式:
1.黑色保活:通过广播相互唤醒。2.白色保活:启动前台service
3.灰色保活:利用系统漏洞启动前台service
黑色保活:
黑色保活这种方式是最为简单的方法,通过系统广播什么拍照,启动,网络连接等等广播,或者其他app的广播进行唤醒。白色保活:
通过启动前台Service来保持应用的一直运行。我们看一下如何让一个service成为前台service,一般情况下我们知道service运行在后台,并且优先级也不高,当内存不够时service就会被回收掉,因此我们要想service一直保持运行,就考虑使用前台service。
前台service与普通service区别在于前台service一直有一个运行图标显示在系统通知栏。类似Notification.
public ForeService extends Service{ public void onCreate(){ super.onCreate(); //创建NOtification对象 Notification notificatin=new Notification(R.drawable.icon,"前台service",System.currentTImeMillis()); Intent intent=new Intent(this,MainActivity.class); PendingIntent pending=PendingIntent.getActivity(this,0,intent,0); //为通知设置布局和数据 notification.setLastestEventInfo(this,"","",pending); //将service设置为前台service startForeground(1,notification); } }
灰色保活:
利用系统漏洞设置前台service对app进行保活,相对白色保活而言,这种方式更为隐蔽。方式按系统分为:
API<18 : 启动前台service,直接传入一个 new Notificaation()
API>18 : 同时启动两个id相同的前台service,然后将后启动的service进行stop操作。
public class GrayService extends Service { private final static int GRAY_SERVICE_ID = 1001; @Override public int onStartCommand(Intent intent, int flags, int startId) { if (Build.VERSION.SDK_INT < 18) { startForeground(GRAY_SERVICE_ID, new Notification());//API < 18 ,此方法能有效隐藏Notification上的图标 } else { Intent innerIntent = new Intent(this, GrayInnerService.class); startService(innerIntent); startForeground(GRAY_SERVICE_ID, new Notification()); } return super.onStartCommand(intent, flags, startId); } ... ... /** * 给 API >= 18 的平台上用的灰色保活手段 */ public static class GrayInnerService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(GRAY_SERVICE_ID, new Notification()); stopForeground(true); stopSelf(); return super.onStartCommand(intent, flags, startId); } }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories