原文出自:http://mzh3344258.blog.51cto.com/1823534/804237
- Object o=new Object();
- Object o1=o;
- o=null;
- o1=null
- String abc=new String("abc"); //1
- SoftReference<String> abcSoftRef=new SoftReference<String>(abc); //2
- WeakReference<String> abcWeakRef = new WeakReference<String>(abc); //3
- abc=null; //4
- abcSoftRef.clear();//5
- Reference(T paramT, ReferenceQueue<? super T>paramReferenceQueue)
- A obj = new A();
- Refenrence sr = new SoftReference(obj);
- //引用时
- if(sr!=null){
- obj = sr.get();
- }else{
- obj = new A();
- sr = new SoftReference(obj);
- }
- String abc=new String("abc");
- WeakReference<String> abcWeakRef = new WeakReference<String>(abc);
- abc=null;
- System.out.println("before gc: "+abcWeakRef.get());
- System.gc();
- System.out.println("after gc: "+abcWeakRef.get());
- A obj = new A();
- WeakReference wr = new WeakReference(obj);
- obj = null;
- //等待一段时间,obj对象就会被垃圾回收
- ...
- if (wr.get()==null) {
- System.out.println("obj 已经被清除了 ");
- } else {
- System.out.println("obj 尚未被清除,其信息是 "+obj.toString());
- }
- ...
- }
- import java.lang.ref.PhantomReference;
- import java.lang.ref.Reference;
- import java.lang.ref.ReferenceQueue;
- import java.lang.reflect.Field;
- public class Test {
- public static boolean isRun = true;
- public static void main(String[] args) throws Exception {
- String abc = new String("abc");
- System.out.println(abc.getClass() + "@" + abc.hashCode());
- final ReferenceQueue referenceQueue = new ReferenceQueue<String>();
- new Thread() {
- public void run() {
- while (isRun) {
- Object o = referenceQueue.poll();
- if (o != null) {
- try {
- Field rereferent = Reference.class
- .getDeclaredField("referent");
- rereferent.setAccessible(true);
- Object result = rereferent.get(o);
- System.out.println("gc will collect:"
- + result.getClass() + "@"
- + result.hashCode());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- }.start();
- PhantomReference<String> abcWeakRef = new PhantomReference<String>(abc,
- referenceQueue);
- abc = null;
- Thread.currentThread().sleep(3000);
- System.gc();
- Thread.currentThread().sleep(3000);
- isRun = false;
- }
- }
- @SuppressWarnings("unused")
- private Bitmap copressImage(String imgPath){
- File picture = new File(imgPath);
- Options bitmapFactoryOptions = new BitmapFactory.Options();
- //下面这个设置是将图片边界不可调节变为可调节
- bitmapFactoryOptions.inJustDecodeBounds = true;
- bitmapFactoryOptions.inSampleSize = 2;
- int outWidth = bitmapFactoryOptions.outWidth;
- int outHeight = bitmapFactoryOptions.outHeight;
- bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
- bitmapFactoryOptions);
- float imagew = 150;
- float imageh = 150;
- int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight
- / imageh);
- int xRatio = (int) Math
- .ceil(bitmapFactoryOptions.outWidth / imagew);
- if (yRatio > 1 || xRatio > 1) {
- if (yRatio > xRatio) {
- bitmapFactoryOptions.inSampleSize = yRatio;
- } else {
- bitmapFactoryOptions.inSampleSize = xRatio;
- }
- }
- bitmapFactoryOptions.inJustDecodeBounds = false;
- bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
- bitmapFactoryOptions);
- if(bmap != null){
- //ivwCouponImage.setImageBitmap(bmap);
- return bmap;
- }
- return null;
- }
- package com.lvguo.scanstreet.activity;
- import java.io.File;
- import java.lang.ref.SoftReference;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.res.TypedArray;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.BitmapFactory.Options;
- import android.os.Bundle;
- import android.view.View;
- import android.view.ViewGroup;
- import android.view.WindowManager;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemLongClickListener;
- import android.widget.BaseAdapter;
- import android.widget.Gallery;
- import android.widget.ImageView;
- import android.widget.Toast;
- import com.lvguo.scanstreet.R;
- import com.lvguo.scanstreet.data.ApplicationData;
- /**
- * @Title: PhotoScanActivity.java
- * @Description: 照片预览控制类
- * @author XiaoMa
- */
- public class PhotoScanActivity extends Activity {
- private Gallery gallery ;
- private List<String> ImageList;
- private List<String> it ;
- private ImageAdapter adapter ;
- private String path ;
- private String shopType;
- private HashMap<String, SoftReference<Bitmap>> imageCache = null;
- private Bitmap bitmap = null;
- private SoftReference<Bitmap> srf = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);
- setContentView(R.layout.photoscan);
- Intent intent = this.getIntent();
- if(intent != null){
- if(intent.getBundleExtra("bundle") != null){
- Bundle bundle = intent.getBundleExtra("bundle");
- path = bundle.getString("path");
- shopType = bundle.getString("shopType");
- }
- }
- init();
- }
- private void init(){
- imageCache = new HashMap<String, SoftReference<Bitmap>>();
- gallery = (Gallery)findViewById(R.id.gallery);
- ImageList = getSD();
- if(ImageList.size() == 0){
- Toast.makeText(getApplicationContext(), "无照片,请返回拍照后再使用预览", Toast.LENGTH_SHORT).show();
- return ;
- }
- adapter = new ImageAdapter(this, ImageList);
- gallery.setAdapter(adapter);
- gallery.setOnItemLongClickListener(longlistener);
- }
- /**
- * Gallery长按事件操作实现
- */
- private OnItemLongClickListener longlistener = new OnItemLongClickListener() {
- @Override
- public boolean onItemLongClick(AdapterView<?> parent, View view,
- final int position, long id) {
- //此处添加长按事件删除照片实现
- AlertDialog.Builder dialog = new AlertDialog.Builder(PhotoScanActivity.this);
- dialog.setIcon(R.drawable.warn);
- dialog.setTitle("删除提示");
- dialog.setMessage("你确定要删除这张照片吗?");
- dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- File file = new File(it.get(position));
- boolean isSuccess;
- if(file.exists()){
- isSuccess = file.delete();
- if(isSuccess){
- ImageList.remove(position);
- adapter.notifyDataSetChanged();
- //gallery.setAdapter(adapter);
- if(ImageList.size() == 0){
- Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoSizeZero), Toast.LENGTH_SHORT).show();
- }
- Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoDelSuccess), Toast.LENGTH_SHORT).show();
- }
- }
- }
- });
- dialog.setNegativeButton("取消",new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- dialog.create().show();
- return false;
- }
- };
- /**
- * 获取SD卡上的所有图片文件
- * @return
- */
- private List<String> getSD() {
- /* 设定目前所在路径 */
- File fileK ;
- it = new ArrayList<String>();
- if("newadd".equals(shopType)){
- //如果是从查看本人新增列表项或商户列表项进来时
- fileK = new File(ApplicationData.TEMP);
- }else{
- //此时为纯粹新增
- fileK = new File(path);
- }
- File[] files = fileK.listFiles();
- if(files != null && files.length>0){
- for(File f : files ){
- if(getImageFile(f.getName())){
- it.add(f.getPath());
- Options bitmapFactoryOptions = new BitmapFactory.Options();
- //下面这个设置是将图片边界不可调节变为可调节
- bitmapFactoryOptions.inJustDecodeBounds = true;
- bitmapFactoryOptions.inSampleSize = 5;
- int outWidth = bitmapFactoryOptions.outWidth;
- int outHeight = bitmapFactoryOptions.outHeight;
- float imagew = 150;
- float imageh = 150;
- int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight
- / imageh);
- int xRatio = (int) Math
- .ceil(bitmapFactoryOptions.outWidth / imagew);
- if (yRatio > 1 || xRatio > 1) {
- if (yRatio > xRatio) {
- bitmapFactoryOptions.inSampleSize = yRatio;
- } else {
- bitmapFactoryOptions.inSampleSize = xRatio;
- }
- }
- bitmapFactoryOptions.inJustDecodeBounds = false;
- bitmap = BitmapFactory.decodeFile(f.getPath(),
- bitmapFactoryOptions);
- //bitmap = BitmapFactory.decodeFile(f.getPath());
- srf = new SoftReference<Bitmap>(bitmap);
- imageCache.put(f.getName(), srf);
- }
- }
- }
- return it;
- }
- /**
- * 获取图片文件方法的具体实现
- * @param fName
- * @return
- */
- private boolean getImageFile(String fName) {
- boolean re;
- /* 取得扩展名 */
- String end = fName
- .substring(fName.lastIndexOf(".") + 1, fName.length())
- .toLowerCase();
- /* 按扩展名的类型决定MimeType */
- if (end.equals("jpg") || end.equals("gif") || end.equals("png")
- || end.equals("jpeg") || end.equals("bmp")) {
- re = true;
- } else {
- re = false;
- }
- return re;
- }
- public class ImageAdapter extends BaseAdapter{
- /* 声明变量 */
- int mGalleryItemBackground;
- private Context mContext;
- private List<String> lis;
- /* ImageAdapter的构造符 */
- public ImageAdapter(Context c, List<String> li) {
- mContext = c;
- lis = li;
- TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
- mGalleryItemBackground = a.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);
- a.recycle();
- }
- /* 几定要重写的方法getCount,传回图片数目 */
- public int getCount() {
- return lis.size();
- }
- /* 一定要重写的方法getItem,传回position */
- public Object getItem(int position) {
- return lis.get(position);
- }
- /* 一定要重写的方法getItemId,传并position */
- public long getItemId(int position) {
- return position;
- }
- /* 几定要重写的方法getView,传并几View对象 */
- public View getView(int position, View convertView, ViewGroup parent) {
- System.out.println("lis:"+lis);
- File file = new File(it.get(position));
- SoftReference<Bitmap> srf = imageCache.get(file.getName());
- Bitmap bit = srf.get();
- ImageView i = new ImageView(mContext);
- i.setImageBitmap(bit);
- i.setScaleType(ImageView.ScaleType.FIT_XY);
- i.setLayoutParams( new Gallery.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
- WindowManager.LayoutParams.WRAP_CONTENT));
- return i;
- }
- }
- }
- 1. InputStream is = this.getResources().openRawResource(R.drawable.pic1);
- BitmapFactory.Options options=new BitmapFactory.Options();
- options.inJustDecodeBounds = false;
- options.inSampleSize = 10; //width,hight设为原来的十分一
- Bitmap btp =BitmapFactory.decodeStream(is,null,options);
- 2. if(!bmp.isRecycle() ){
- bmp.recycle() //回收图片所占的内存
- system.gc() //提醒系统及时回收
- }
- /** 这个地方大家别搞混了,为了方便小马把两个贴一起了,使用的时候记得分开使用
- * 以最省内存的方式读取本地资源的图片
- */
- public static Bitmap readBitMap(Context context, int resId){
- BitmapFactory.Options opt = new BitmapFactory.Options();
- opt.inPreferredConfig = Bitmap.Config.RGB_565;
- opt.inPurgeable = true;
- opt.inInputShareable = true;
- //获取资源图片
- InputStream is = context.getResources().openRawResource(resId);
- return BitmapFactory.decodeStream(is,null,opt);
- }
- if(bitmapObject.isRecycled()==false) //如果没有回收
- bitmapObject.recycle();
- private final static floatTARGET_HEAP_UTILIZATION = 0.75f;
- 在程序onCreate时就可以调用
- VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
- 即可
- private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
- //设置最小heap内存为6MB大小
- VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);
本文出自 “酷_莫名简单、KNothing” 博客,请务必保留此出处http://mzh3344258.blog.51cto.com/1823534/804237