看了一篇写的非常不错
Android 操作系统的内存回收机制 http://www.oschina.net/question/129540_64132
总结一下有一下几点:
- 必须是非 persistent 进程,即非系统进程;
- 必须是空进程,即进程中没有任何 activity 存在。如果杀死存在 Activity 的进程,有可能关闭用户正在使用的程序,或者使应用程序恢复的时延变大,从而影响用户体验;
- 必须无 broadcast receiver。运行 broadcast receiver 一般都在等待一个事件的发生,用户并不希望此类程序被系统强制关闭;
- 进程中 service 的数量必须为 0。存在 service 的进程很有可能在为一个或者多个程序提供某种服务,如 GPS 定位服务。杀死此类进程将使其他进程无法正常服务。
这个时候才会杀掉进程。
具体代码只粘贴一下,需要详细讲解请那片文章
final void trimApplications()
{
synchronized(this)
{
for(int i = mRemovedProcesses.size() - 1; i >= 0; i--)
{
ProcessRecord app = (ProcessRecord)mRemovedProcesses.get(i);
if(app.activities.size() != 0 || app.curReceiver != null || app.services.size() != 0)
continue;
Slog.i("ActivityManager", (new StringBuilder()).append("Exiting empty application process ").append(app.processName).append(" (").append(app.thread == null ? null : ((Object) (app.thread.asBinder()))).append(")\n").toString());
if(app.pid > 0 && app.pid != MY_PID)
{
EventLog.writeEvent(30023, new Object[] {
Integer.valueOf(app.pid), app.processName, Integer.valueOf(app.setAdj), "empty"
});
Process.killProcessQuiet(app.pid);
} else
{
try
{
app.thread.scheduleExit();
}
catch(Exception e) { }
}
cleanUpApplicationRecordLocked(app, false, true, -1);
mRemovedProcesses.remove(i);
if(app.persistent && app.persistent)
addAppLocked(app.info, false);
}
updateOomAdjLocked();
}
}
下面讲解一下自己的心得
1. 用Notification绑定Service,让Service优先级别高,不过,这样需要通知栏一直显示图标,具体代码
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.ic_launcher,
"Hello,there!", System.currentTimeMillis());
n.flags = Notification.FLAG_ONGOING_EVENT;
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
// PendingIntent
PendingIntent contentIntent = PendingIntent.getActivity(this,
R.string.app_name, i, PendingIntent.FLAG_UPDATE_CURRENT);
n.setLatestEventInfo(this, "Hello,there!", "Hello,there,I'm john.",
contentIntent);
nm.notify(R.string.app_name, n);
2.待续