1. 程式人生 > >Handler在Activity和Fragment中的記憶體洩露問題

Handler在Activity和Fragment中的記憶體洩露問題

解決方法:將handler宣告為static靜態方法

在activity中:

private final MyHandler handler=new MyHandler(this);//在activity中宣告handler

private static class MyHandler extends Handler {

private final WeakReference mActivityReference;

MyHandler(Activity activity) {

this.mActivityReference=new WeakReference<>(activity);

}

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

final MainActivity activity = (MainActivity)mActivityReference.get();//獲取弱引用佇列中的activity

if(activity!=null){

switch(msg.what) {//獲取訊息,更新UI

}

}

}

}

//訊息佇列裡面的訊息移除

@Override

protected voidonDestroy() {

super.onDestroy();

_handler.removeCallbacksAndMessages(null);

context=null;

}



在fragment中

private final MyHandler handler=new MyHandler(this);//在activity中宣告handler

private static class MyHandler extends Handler {

private final WeakReference mFragmentReference;

MyHandler(Fragment fragment) {

this.mFragmentReference=new WeakReference<>(fragment);

}

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

final MainFragment fragment= (MainFragment)mFragmentReference.get();

if(fragment!=null){

switch(msg.what) {//獲取訊息,更新UI

}

}

}

}

//訊息佇列裡面的訊息移除

@Override

protected voidonDestroy() {

super.onDestroy();

_handler.removeCallbacksAndMessages(null);

}