Android学习笔记之SoftReference软引用,弱引用WeakReference
生活随笔
收集整理的這篇文章主要介紹了
Android学习笔记之SoftReference软引用,弱引用WeakReference
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SoftReference可以用于bitmap緩存
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);}@Overridepublic 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);}@Overridepublic 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;}@Overridepublic 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 hereif ((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]);} }}} }?
轉載于:https://www.cnblogs.com/lipeineng/p/6904139.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Android学习笔记之SoftReference软引用,弱引用WeakReference的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 获取系统当前时间
- 下一篇: Android性能优化——使用 APK