从Android设备加载所有图像时的性能问题

时间:2014-04-11 12:47:19

标签: android performance android-asynctask android-gridview mediastore

我已经看过其他 SO 问题并且已经尝试了他们的解决方案,但没有帮助,所以我自己要求

我在使用“GridView”中的设备加载所有图片时遇到问题,我使用的是MediaStore'获取图像,我非常成功,并且我已经将所有图像文件分开了

我的手机有1 GB内存,所以我可以毫无困难地加载图像, 但我面临的问题是,当我使用另一台设备时,我的手机的内存少了很多时间来加载图片,有时它只是不加载我已经尝试过的任何图像& #39;的AsyncTask'但它没有帮助。

以下是我到目前为止所做的事情:

public class DirectoryImagesActivity extends Activity {

private ImageAdapter imageAdapter;

public static String[] arrPath;
private boolean[] thumbnailsselection;
private int ids[];
private int count;
Bundle dirBundle;
String dirName;
public static Bitmap[] imageThumb;
ArrayList<Bitmap> dirBitmap = new ArrayList<Bitmap>();

/**
 * Overrides methods
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photo_gallery);

    dirBundle = getIntent().getExtras();

    dirName = dirBundle.getString("dir_name");

    String[] projectionFolder = { MediaStore.Images.Media._ID,
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
            MediaStore.Images.Media.DATA };
    String selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " = ?";
    String[] selectionArgs = new String[] { dirName };
    @SuppressWarnings("deprecation")
    Cursor mImageCursor = managedQuery(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projectionFolder,
            selection, selectionArgs, null);

    int image_column_index = mImageCursor
            .getColumnIndex(MediaStore.Images.Media._ID);
    this.count = mImageCursor.getCount();
    arrPath = new String[this.count];
    imageThumb = new Bitmap[this.count];
    ids = new int[count];
    this.thumbnailsselection = new boolean[this.count];
    for (int i = 0; i < this.count; i++) {
        mImageCursor.moveToPosition(i);
        ids[i] = mImageCursor.getInt(image_column_index);
        int dataColumnIndex = mImageCursor
                .getColumnIndex(MediaStore.Images.Media.DATA);
        arrPath[i] = mImageCursor.getString(dataColumnIndex);
        int id = mImageCursor.getInt(mImageCursor
                .getColumnIndex(MediaStore.MediaColumns._ID));

        dirBitmap.add(MediaStore.Images.Thumbnails.getThumbnail(
                getContentResolver(), id,
                MediaStore.Images.Thumbnails.MICRO_KIND, null));

    }
    GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imageAdapter = new ImageAdapter(this);
    imagegrid.setAdapter(imageAdapter);
    // imagecursor.close();

    final Button selectBtn = (Button) findViewById(R.id.selectBtn);
    selectBtn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            final int len = thumbnailsselection.length;
            int cnt = 0;
            String selectImages = "";
            for (int i = 0; i < len; i++) {
                if (thumbnailsselection[i]) {
                    cnt++;
                    selectImages = selectImages + arrPath[i] + "|";
                }
            }
            if (cnt == 0) {
                Toast.makeText(getApplicationContext(),
                        "Please select at least one image",
                        Toast.LENGTH_LONG).show();
            } else {

                Log.d("SelectedImages", selectImages);
                Intent i = new Intent();
                i.putExtra("data", selectImages);
                setResult(Activity.RESULT_OK, i);
                finish();
            }
        }
    });
}

@Override
public void onBackPressed() {
    setResult(Activity.RESULT_CANCELED);
    super.onBackPressed();

}

/**
 * Class method
 */

/**
 * This method used to set bitmap.
 * 
 * @param iv
 *            represented ImageView
 * @param id
 *            represented id
 */

public void setBitmap(final ImageView iv, final Bitmap id) {

    new AsyncTask<Void, Void, Bitmap>() {

        @Override
        protected Bitmap doInBackground(Void... params) {

            return id;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            iv.setImageBitmap(result);
        }
    }.execute();
}

/**
 * List adapter
 * 
 * @author tasol
 */

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    public ImageLoader imageLoader;
    Context context;

    public ImageAdapter(Context context) {
        this.context = context;
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader = new ImageLoader(context);

    }

    public int getCount() {
        return dirBitmap.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView,
            ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.layout_improved_grid,
                    null);
            holder.imageview = (SquareImageView) convertView
                    .findViewById(R.id.thumbImage);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.imageview.setId(position);

        // holder.imageview.setImageBitmap(imageThumb[position]);
        holder.imageview.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Toast.makeText(DirectoryImagesActivity.this,
                        "Item Clicked", Toast.LENGTH_LONG).show();

                Intent i = new Intent(getApplicationContext(),
                        FullImageActivity.class); // passing array index
                i.putExtra("id", position);
                startActivity(i);

            }
        });

        try {
            setBitmap(holder.imageview, dirBitmap.get(position));
        } catch (Throwable e) {

        }

        holder.id = position;
        return convertView;
    }
}

/**
 * Inner class
 * 
 * @author tasol
 */
class ViewHolder {
    SquareImageView imageview;
    int id;
}

public static Bitmap convertBitmap(String path) {

    Bitmap bitmap = null;
    BitmapFactory.Options bfOptions = new BitmapFactory.Options();
    bfOptions.inDither = false; // Disable Dithering mode
    bfOptions.inPurgeable = true; // Tell to gc that whether it needs free
                                    // memory, the Bitmap can be cleared
    bfOptions.inInputShareable = true; // Which kind of reference will be
                                        // used to recover the Bitmap data
                                        // after being clear, when it will
                                        // be used in the future
    bfOptions.inTempStorage = new byte[32 * 1024];

    File file = new File(path);
    FileInputStream fs = null;
    try {
        fs = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try {
        if (fs != null) {
            bitmap = BitmapFactory.decodeFileDescriptor(fs.getFD(), null,
                    bfOptions);
        }
    } catch (IOException e) {

        e.printStackTrace();
    } finally {
        if (fs != null) {
            try {
                fs.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

    return bitmap;
}

}

如果有人可以帮我提前谢谢你

2 个答案:

答案 0 :(得分:0)

由于您要加载的图片很多,因此必须按顺序实施延迟加载,以提高其他内存设备的应用性能。 您可以参考此库https://github.com/nostra13/Android-Universal-Image-Loader。 我希望这会有所帮助。

答案 1 :(得分:0)

试试这是有效的解决方案

<强> 1)PhotoGalaryActivity.java

public class PhotoGalaryActivity extends Activity {

    private ImageAdapter imageAdapter;

    private String[] arrPath;
    private boolean[] thumbnailsselection;
    private int ids[];
    private int count;


    /**
     * Overrides methods
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_gallery);

        final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media._ID;
        @SuppressWarnings("deprecation")
        Cursor imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
        int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
        this.count = imagecursor.getCount();
        this.arrPath = new String[this.count];
        ids = new int[count];
        this.thumbnailsselection = new boolean[this.count];
        for (int i = 0; i < this.count; i++) {
            imagecursor.moveToPosition(i);
            ids[i] = imagecursor.getInt(image_column_index);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            arrPath[i] = imagecursor.getString(dataColumnIndex);
        }
        GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
        imageAdapter = new ImageAdapter();
        imagegrid.setAdapter(imageAdapter);
        imagecursor.close();

        final Button selectBtn = (Button) findViewById(R.id.selectBtn);
        selectBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                final int len = thumbnailsselection.length;
                int cnt = 0;
                String selectImages = "";
                for (int i = 0; i < len; i++) {
                    if (thumbnailsselection[i]) {
                        cnt++;
                        selectImages = selectImages + arrPath[i] + "|";
                    }
                }
                if (cnt == 0) {
                    Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
                } else {

                    Log.d("SelectedImages", selectImages);
                    Intent i = new Intent();
                    i.putExtra("data", selectImages);
                    setResult(Activity.RESULT_OK, i);
                    finish();
                }
            }
        });
    }
    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_CANCELED);
        super.onBackPressed();

    }

    /**
     * Class method
     */

    /**
     * This method used to set bitmap.
     * @param iv represented ImageView 
     * @param id represented id
     */

    private void setBitmap(final ImageView iv, final int id) {

        new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Void... params) {

                return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
                iv.setImageBitmap(result);
            }
        }.execute();
    }


    /**
     * List adapter
     * @author tasol
     */

    public class ImageAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public ImageAdapter() {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.photo_gallery_item, null);
                holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
                holder.checkBox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.checkBox.setId(position);
            holder.imageview.setId(position);
            holder.checkBox.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (thumbnailsselection[id]) {
                        cb.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        cb.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });
            holder.imageview.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    int id = holder.checkBox.getId();
                    if (thumbnailsselection[id]) {
                        holder.checkBox.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        holder.checkBox.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });
            try {
                setBitmap(holder.imageview, ids[position]);
            } catch (Throwable e) {
            }
            holder.checkBox.setChecked(thumbnailsselection[position]);
            holder.id = position;
            return convertView;
        }
    }


    /**
     * Inner class
     * @author tasol
     */
    class ViewHolder {
        ImageView imageview;
        CheckBox checkBox;
        int id;
    }

}

<强> 2)photo_gallery.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView android:id="@+id/thumbImage" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_centerInParent="true" 
        />
    <CheckBox android:id="@+id/itemCheckBox" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />
</RelativeLayout>

第3)photo_gallery_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView android:id="@+id/thumbImage" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_centerInParent="true" 
        />
    <CheckBox android:id="@+id/itemCheckBox" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />
</RelativeLayout>