在Android開發中,基本上不多有用到軟引用或弱引用,這兩個東東若用的很好,對本身開發的代碼質量的提升有很大的幫助。若用的很差,會坑了本身。因此,在尚未真正的去了解它們以前,仍是慎用比較好。html
下面將經過兩個Demo來結識軟引用和弱引用在開發中的運用。java
一. WeakReference:防止內存泄漏,要保證內存被虛擬機回收。android
下面以一個時間更新的Demo來講明弱引用的運用。git
1. main.xml文件代碼以下: canvas
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <com.stevenhu.wrt.DigitalClock
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal">
-
- <TextView android:id="@+id/time"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="50pt"
- />
-
- <TextView android:id="@+id/ampm"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="25pt"
- />
-
- </com.stevenhu.wrt.DigitalClock>
-
- </LinearLayout>
2.自定義ViewGroup類DigitalClock的代碼以下:緩存
- package com.stevenhu.wrt;
-
- import java.lang.ref.WeakReference;
- import java.text.DateFormatSymbols;
- import java.util.Calendar;
-
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.database.ContentObserver;
- import android.graphics.Canvas;
- import android.os.Handler;
- import android.provider.Settings;
- import android.text.format.DateFormat;
- import android.util.AttributeSet;
- import android.view.View;
- import android.widget.LinearLayout;
- import android.widget.TextView;
- import android.widget.Toast;
-
- public class DigitalClock extends LinearLayout {
-
- private final static String M12 = "h:mm";
- private final static String M24 = "kk:mm";
-
- private Calendar mCalendar;
- private String mFormat;
- private TextView mDislpayTime;
- private AmPm mAmPm;
- private ContentObserver mFormatChangeObserver;
- private final Handler mHandler = new Handler();
- private BroadcastReceiver mReceiver;
- private Context mContext;
-
- public DigitalClock(Context context, AttributeSet attrs) {
- super(context, attrs);
- mContext = context;
-
- }
-
- @Override
- protected void onFinishInflate() {
-
- super.onFinishInflate();
- mDislpayTime = (TextView) this.findViewById(R.id.time);
- mAmPm = new AmPm(this);
- mCalendar = Calendar.getInstance();
-
- setDateFormat();
- }
-
- @Override
- protected void onAttachedToWindow() {
-
- super.onAttachedToWindow();
-
-
- if (mReceiver == null) {
- mReceiver = new TimeChangedReceiver(this);
- IntentFilter filter = new IntentFilter();
- filter.addAction(Intent.ACTION_TIME_TICK);
- filter.addAction(Intent.ACTION_TIME_CHANGED);
- filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
- mContext.registerReceiver(mReceiver, filter);
- }
-
-
- if (mFormatChangeObserver == null) {
- mFormatChangeObserver = new FormatChangeObserver(this);
- mContext.getContentResolver().registerContentObserver(
- Settings.System.CONTENT_URI, true, mFormatChangeObserver);
- }
-
-
- updateTime();
- }
-
- @Override
- protected void onDetachedFromWindow() {
-
- super.onDetachedFromWindow();
-
- if (mReceiver != null) {
- mContext.unregisterReceiver(mReceiver);
- }
- if (mFormatChangeObserver != null) {
- mContext.getContentResolver().unregisterContentObserver(
- mFormatChangeObserver);
- }
-
- mFormatChangeObserver = null;
- mReceiver = null;
- }
-
- static class AmPm {
- private TextView mAmPmTextView;
- private String mAmString, mPmString;
-
- AmPm(View parent) {
- mAmPmTextView = (TextView) parent.findViewById(R.id.ampm);
- String[] ampm = new DateFormatSymbols().getAmPmStrings();
- mAmString = ampm[0];
- mPmString = ampm[1];
- }
-
- void setShowAmPm(boolean show) {
- if (mAmPmTextView != null) {
- mAmPmTextView.setVisibility(show ? View.VISIBLE : View.GONE);
- }
- }
-
- void setIsMorning(boolean isMorning) {
- if (mAmPmTextView != null) {
- mAmPmTextView.setText(isMorning ? mAmString : mPmString);
- }
- }
- }
-
-
- private static class TimeChangedReceiver extends BroadcastReceiver {
-
-
- private WeakReference<DigitalClock> mClock;
- private Context mContext;
-
- public TimeChangedReceiver(DigitalClock clock) {
- mClock = new WeakReference<DigitalClock>(clock);
- mContext = clock.getContext();
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
-
-
- final boolean timezoneChanged = intent.getAction().equals(
- Intent.ACTION_TIMEZONE_CHANGED);
-
- final DigitalClock clock = mClock.get();
- if (clock != null) {
- clock.mHandler.post(new Runnable() {
- public void run() {
- if (timezoneChanged) {
- clock.mCalendar = Calendar.getInstance();
- }
- clock.updateTime();
- }
- });
- } else {
- try {
- mContext.unregisterReceiver(this);
- } catch (RuntimeException e) {
-
- }
- }
- }
- };
-
-
- private static class FormatChangeObserver extends ContentObserver {
-
- private WeakReference<DigitalClock> mClock;
- private Context mContext;
-
- public FormatChangeObserver(DigitalClock clock) {
- super(new Handler());
- mClock = new WeakReference<DigitalClock>(clock);
- mContext = clock.getContext();
- }
-
- @Override
- public void onChange(boolean selfChange) {
- DigitalClock digitalClock = mClock.get();
-
- if (digitalClock != null) {
-
- digitalClock.setDateFormat();
- digitalClock.updateTime();
- } else {
- try {
- mContext.getContentResolver().unregisterContentObserver(
- this);
- } catch (RuntimeException e) {
-
- }
- }
- }
- }
-
-
- private void updateTime() {
- Toast.makeText(mContext, "updateTime", Toast.LENGTH_SHORT).show();
- mCalendar.setTimeInMillis(System.currentTimeMillis());
-
- CharSequence newTime = DateFormat.format(mFormat, mCalendar);
- mDislpayTime.setText(newTime);
- mAmPm.setIsMorning(mCalendar.get(Calendar.AM_PM) == 0);
- }
-
- private void setDateFormat() {
-
- mFormat = android.text.format.DateFormat.is24HourFormat(getContext()) ? M24
- : M12;
-
- mAmPm.setShowAmPm(mFormat.equals(M12));
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
-
- super.onDraw(canvas);
-
- }
- }
3.MainActivity的代碼以下: 網絡
- package com.stevenhu.wrt;
-
- import android.app.Activity;
- import android.os.Bundle;
-
- public class MainActivity extends Activity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
- }
二. SoftReference:實現緩存機制app
下面的Demo實現從網絡上獲取圖片,而後將獲取的圖片顯示的同時,經過軟引用緩存起來。當下次再去網絡上獲取圖片時,首先會檢查要獲取的圖片緩存中是否存在,若存在,直接取出來,不須要再去網絡上獲取。異步
1.main.xml文件代碼以下:ide
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/get_image"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="get Image"/>
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <ImageView
- android:id="@+id/one"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
-
- <ImageView
- android:id="@+id/two"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
-
- <ImageView
- android:id="@+id/three"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
- </LinearLayout>
-
- </LinearLayout>
2.實現異步加載圖片功能的類AsyncImageLoader代碼以下:
- package com.stevenhu.lit;
-
- import java.lang.ref.SoftReference;
- import java.net.URL;
- import java.util.HashMap;
- import java.util.Map;
-
- import android.graphics.drawable.Drawable;
- import android.os.Handler;
- import android.os.Message;
-
- public class AsyncImageLoader
- {
-
- private Map<String, SoftReference<Drawable>> mImageCache =
- new HashMap<String, SoftReference<Drawable>>();
-
-
- public Drawable loadDrawable(final String imageUrl, final ImageCallback callback)
- {
-
- if(mImageCache.containsKey(imageUrl))
- {
- SoftReference<Drawable> softReference = mImageCache.get(imageUrl);
- if (softReference.get() != null)
- {
- return softReference.get();
- }
- }
-
- final Handler handler = new Handler()
- {
- @Override
- public void dispatchMessage(Message msg)
- {
-
- callback.imageLoad((Drawable)msg.obj);
- }
- };
-
-
- new Thread()
- {
- public void run()
- {
- Drawable drawable = loadImageFromUrl(imageUrl);
-
- mImageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
- Message message = handler.obtainMessage(0, drawable);
- handler.sendMessage(message);
- };
- }.start();
-
-
- return null;
-
- }
-
-
- public interface ImageCallback
- {
- void imageLoad(Drawable drawable);
- }
-
-
- protected Drawable loadImageFromUrl(String imageUrl)
- {
- try {
- return Drawable.createFromStream(new URL(imageUrl).openStream(),"debug");
- } catch (Exception e) {
-
- throw new RuntimeException(e);
- }
- }
- }
3. 實現ImageCallback回調接口的類ImageCallbackImpl代碼以下:
- package com.stevenhu.lit;
-
- import android.graphics.drawable.Drawable;
- import android.widget.ImageView;
-
- import com.stevenhu.lit.AsyncImageLoader.ImageCallback;
-
- public class ImageCallbackImpl implements ImageCallback
- {
-
- private ImageView mImageView;
-
- public ImageCallbackImpl(ImageView imageView)
- {
- mImageView = imageView;
- }
-
-
- @Override
- public void imageLoad(Drawable drawable)
- {
-
- mImageView.setImageDrawable(drawable);
- }
-
- }
4.MainActivity的代碼以下:
- package com.stevenhu.lit;
-
-
- import android.app.Activity;
- import android.graphics.drawable.Drawable;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ImageView;
-
- public class MainActivity extends Activity implements OnClickListener
- {
-
- private AsyncImageLoader mImageLoader = new AsyncImageLoader();
-
-
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
-
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button get = (Button)findViewById(R.id.get_image);
- get.setOnClickListener(this);
- }
-
- private void loadImage(final String url, final int id)
- {
- ImageView imageView = (ImageView)findViewById(id);
- ImageCallbackImpl callbackImpl = new ImageCallbackImpl(imageView);
- Drawable cacheImage = mImageLoader.loadDrawable(url, callbackImpl);
-
- if (cacheImage != null)
- {
- imageView.setImageDrawable(cacheImage);
- }
- }
-
- @Override
- public void onClick(View v) {
-
- if (v.getId() == R.id.get_image)
- {
-
- loadImage("http://wenwen.soso.com/p/20111003/20111003194816-1615366606.jpg", R.id.one);
- loadImage("http://t10.baidu.com/it/u=2492256852,4267838923&fm=23&gp=0.jpg", R.id.two);
- loadImage("http://wenwen.soso.com/p/20100410/20100410102416-1948049438.jpg", R.id.three);
- }
-
- }
-
- }
最後,對於這二者,做個小總結:
1. SoftReference<T>:軟引用-->當虛擬機內存不足時,將會回收它指向的對象;須要獲取對象時,能夠調用get方法。
2. WeakReference<T>:弱引用-->隨時可能會被垃圾回收器回收,不必定要等到虛擬機內存不足時才強制回收。要獲取對象時,一樣能夠調用get方法。
3. WeakReference通常用來防止內存泄漏,要保證內存被虛擬機回收,SoftReference多用做來實現緩存機制(cache);
note:轉自http://blog.csdn.net/stevenhu_223/article/details/18360397