WeakReference 可以用于handler
非静态内部类和匿名内部类容易造成内存泄漏
private Handler mRemoteHandler = new SafeHandler(this); private static final int INIT_UI = 1; /** * safe handler 静态内部类 */ private static class SafeHandler extends Handler { private final WeakReference<MainActivity> mActivitys; public SafeHandler(MainActivity preview) { mActivitys = new WeakReference<MainActivity>(preview); } @Override public void handleMessage(Message msg) { MainActivity activity = mActivitys.get(); if (activity != null) { if (null != msg) { switch (msg.what) { case INIT_UI: activity.initView(); activity.updateUI(); break; default: break; } } } } }
import android.os.AsyncTask; import android.text.TextUtils; import com.roadrover.settings.network.NetSupplier; import com.roadrover.settings.network.NetworkBean; import com.roadrover.utils.Logcat; import java.lang.ref.WeakReference; import java.util.Arrays; /** 不是内部类 */ public class HotSpotSafeTask extends AsyncTask<Void, Void, String[]> { // 弱引用允许Activity被垃圾收集器清理 private final WeakReference<HotSpotFragment> weakFragment; public HotSpotSafeTask(HotSpotFragment fragment) { this.weakFragment = new WeakReference<>(fragment); } @Override public String[] doInBackground(Void... params) { // do async stuff here // 重新获取Fragment的强引用,并且判断是否存活 HotSpotFragment fragment = weakFragment.get(); if (fragment == null || fragment.isDetached()) { // Fragment死亡了,不再做任何的事情 return null; } String[] config = fragment.getWifiApConfig(); return config; } @Override public void onPostExecute(String[] config) { // 重新获取Fragment的强引用,并且判断是否存活 HotSpotFragment fragment = weakFragment.get(); if (fragment == null || fragment.isDetached()) { // Fragment死亡了,不再做任何的事情 return; } // The Fragment is still valid, do main-thread stuff here if ((config != null) && (config.length == 3)) { if (null != fragment) { Logcat.d("getWifiApConfig " + Arrays.toString(config)); fragment.setName(config[0]); if (!TextUtils.isEmpty(config[1])) { fragment.setPassword(config[1]); } } } } }