解决oom最终杀手锏(Application中onLowMemory方法)
在内存不足时,杀死部分Activity
1、写一个类MyApp继承Application,重写onLowMemory()方法 2、在该方法中发送广播,该广播用于杀死接收到该广播事件的Activity 3、在清单中注册 package cn.zengfansheng.douban;
import android.app.Application;
import android.content.Intent;
public class MyApp extends Application {
@Override
public void onLowMemory() {
super.onLowMemory();
// 在内存不足时,发送广播,杀死部分注册了该广播的Activity
// 发送一些广播 关闭掉一些activity service
Intent intent = new Intent();
intent.setAction("kill_activity_action");
sendBroadcast(intent);
}
} |
4、在某个Activity中注册该广播 // NOTES==================广播接收者===================
/**
* 杀死当前Acitvity广播接收者
*
* @author hacket
*
*/
private class KillReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
iconCacheMap = null;
showToast("内存不足activity退出");
finish();
}
}
@Override
protected void onStart() {
super.onStart();
// 注册广播接收者
receiver = new KillReceiver();
IntentFilter filter = new IntentFilter("kill_activity_action");
registerReceiver(receiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (receiver != null) {
// 取消注册广播接收者
unregisterReceiver(receiver);
}
}
|
|