怎样使一个Android应用不被杀死?
来源:互联网 发布:建模 软件 数据 开源 编辑:程序博客网 时间:2024/04/30 12:40
参考:http://blog.csdn.net/windskier/article/details/6560925
http://blog.csdn.net/zmyde2010/article/details/6756368
http://blog.sina.com.cn/s/blog_514048cb0100wi2j.html
方法:
对于一个service,可以首先把它设为在前台运行:
public void MyService.onCreate() {
super.onCreate();
Notification notification = new Notification(android.R.drawable.my_service_icon,
"my_service_name",
System.currentTimeMillis());
PendingIntent p_intent = PendingIntent.getActivity(this, 0,
new Intent(this, MyMainActivity.class), 0);
notification.setLatestEventInfo(this, "MyServiceNotification, "MyServiceNotification is Running!", p_intent);
Log.d(TAG, String.format("notification = %s", notification));
startForeground(0x1982, notification); // notification ID: 0x1982, you can name it as you will.
}
-------------------------------
相较于/data/app下的应用,放在/system/app下的应用享受更多的特权,比如若在其Manifest.xml文件中设置persistent属性为true,则可使其免受out-of-memory killer的影响。如应用程序'Phone'的AndroidManifest.xml文件:
<application android:name="PhoneApp"
android:persistent="true"
android:label="@string/dialerIconLabel"
android:icon="@drawable/ic_launcher_phone">
...
</application>
设置后app提升为系统核心级别,任何情况下不会被kill掉, settings->applications里面也会屏蔽掉stop操作。
这样设置前的log: Proc #19: adj=svc /B 4067b028 255:com.xxx.xxx/10001 (started-services)
}
-------------------------------
相较于/data/app下的应用,放在/system/app下的应用享受更多的特权,比如若在其Manifest.xml文件中设置persistent属性为true,则可使其免受out-of-memory killer的影响。如应用程序'Phone'的AndroidManifest.xml文件:
设置后app提升为系统核心级别,任何情况下不会被kill掉, settings->applications里面也会屏蔽掉stop操作。
这样设置前的log:
设置后的log: PERS #19: adj=core /F 406291f0 155:com.xxx.xxx/10001 (fixed)
注:init进程的oom_adj为-16(即SYSTEM_ADJ): cat
Android相关部分分析:
在文件frameworks/base/services/java/com/android/server/am/ActivityManagerService.java中有以下的代码:
可见要想成为core service (即app.maxAdj = CORE_SERVER_ADJ(-12)),应用程序需要FLAG_SYSTEM和FLAG_PERSISTENT两个标志,FLAG_SYSTEM指的是应用位于/system/app下,FLAG_PERSISTENT就是指persistent属性。
而对于frameworks/base/services/java/com/android/server/SystemServer.java,则调用
把自己的 app.maxAdj 设置成SYSTEM_ADJ,即-16。
原理:
Android中的进程是托管的,当系统进程空间紧张的时候,会依照优先级自动进行进程的回收。由此带来三个问题:
Android将进程分为6个等级,它们按优先级顺序由高到低依次是:
特征:
1.如果一个进程里面同时包含service和可视的activity,那么这个进程应该归于可视进程,而不是service进程。
2.另外,如果其他进程依赖于它的话,一个进程的等级可以提高。例如,一个A进程里的service被绑定到B进程里的组件上,进程A将总被认为至少和B进程一样重要。
3.系统中的phone服务被划分到前台进程而不是次要服务进程.
在android中,进程的oom_adj值也就代表了它的优先级。oom_adj值越高代表该进程优先级越低。文件/init.rc中有以下属性设置: