内存不足多张照片上传

时间:2014-08-26 03:49:16

标签: android image upload imageview

我正在尝试将几张照片从我的Android应用程序上传到服务器。我收到内存不足错误。我的图像选择代码如下

单击选择图像按钮时触发的代码


public void triggerImageSelection(View view) {
    int triggeringView = Integer.parseInt((String) view.getTag());
    Log.v(DBUG, "tag of the view:" + triggeringView);
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),
            triggeringView);
}

onActivityResult部分代码如下:


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    Log.v(DBUG, "request code:: " + requestCode);
    switch (requestCode) {
    case 0:
        if (resultCode == RESULT_OK) {
            filePaths[0] = getPath(data.getData());
            File filewe = new File(getPath(data.getData()));
            Bitmap bitmap1 = BitmapFactory.decodeFile(getPath(data
                    .getData()));
            mAdImage1.setImageBitmap(bitmap1);
            if (filewe != null)
                Log.v(DBUG, "got file" + filePaths[0]);
            mAdImage1.setVisibility(View.VISIBLE);

        }

        break;

getPath(); function返回文件路径,如下所示


private String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null,
            null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String filePath = cursor.getString(column_index);
    cursor.close();
    return filePath;
}

我有四个按钮用于选择四个图像。它第一次正常工作,但第二次显示内存不足异常。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

从文件中读取时尝试降低图像质量,如下所示

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 6; 
Bitmap bitmap1 = BitmapFactory.decodeFile(getPath(data.getData()),options); 
mAdImage1.setImageBitmap(bitmap1);
bitmap1.recycle();
bitmap1=null;

如果问题仍然存在,请在清单文件的应用程序标记中使用android:largeHeap="true"

答案 1 :(得分:0)

这里的问题是每次创建新的Bitmap时,旧的Bitmaps仍然存在于内存中。 GC会在决定时收集它。

如果是Bitmaps,建议通知GC垃圾收集对象。我建议采用以下方法。希望这有助于!

  1. 缓存当前显示的位图。如果您已经缓存了位图,请不要调用BitmapFactory.decodeFile(getPath(data.getData()));相反,请使用缓存的。
  2. 每当活动被销毁时,请回收位图,如下所示。需要从onDestroy活动方法调用此方法。 destroy意味着我们现在不需要位图。 参考:http://developer.android.com/reference/android/graphics/Bitmap.html#recycle()

    public void recycleBitmap(Bitmap bitmap) {
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
                System.gc();
            }
        }
    
相关问题