我正在使用動態視圖。我正在運行一項服務。當該服務收到廣播時,我將Myview添加到窗口管理器,並在用戶執行某些操作後刪除它。但是因爲服務一直在運行,所以我每次收到廣播時都會添加這個動態視圖'myView'。問題在於,在從窗口管理器中刪除它們並且堆內存分配不斷增加之後,它們沒有被垃圾收集。不知道爲什麼?因爲它裏面有位圖。 5-6行動後,我得到OutOfMemoryException。從服務創建的動態視圖沒有收集垃圾
public class Myservice extends Service{
private ParentView myView;
WakeReceiver receiver;
@Override
public void onCreate()
{
super.onCreate();
registerBroadCastReceiver();
}
//Performed when broadcast recieved
public void addLayout() {
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
myView = new ParentView(this);
windowManager.addView(myView, getLayoutParam());
}
//Performed when user performs action on ParentView
public void removeLayout() {
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.removeView(myView);
}
private void registerBroadCastReceiver() {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
receiver = new WakeReceiver();
registerReceiver(receiver, filter);
}
private WindowManager.LayoutParams getLayoutParam() {
WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
localLayoutParams.height = (int) (WindowManager.LayoutParams.MATCH_PARENT);
return localLayoutParams;
}
}
//規範父視圖
public class ParentView extends RelativeLayout {
MyService topService;
public ParentView(MyService topService) {
super(topService);
this.topService = topService;
LayoutInflater.from(topService).inflate(R.layout.parent_layout, this);
setBackgroundDrawable(topService.getResources()
.getDrawable(R.drawable.sample_image));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
topService.removeLayout();
}
}
請提供ParentView的代碼。看起來您正在存儲指向某些資源的鏈接,這就阻止了垃圾回收。 – Stepango
'removeView'方法有什麼作用嗎?我的意思是,這個視圖實際上被刪除了嗎? – Haspemulator
'static'不會得到gc,除非這個過程完成了,否則你必須在ondestroy中將它清空。 –