开发者

Android setImageURI out of memory error

I have a very small activity that must show an image.

If picture is not very small (for example 1.12 Mb 2560x1920) it produces out of memory on change screen orientation. I tried getDrawable.setCallback(null) but no luck.

Where am I wrong?

public class Fullscreen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    System.gc();
    setContentView(R.layout.fullscreen);
    ImageView imageView = (ImageView) findViewById(R.id.full_screen_image);
    long imageId = 2;
    imageView.setImageURI(Uri.withAppendedPath开发者_开发技巧(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageId));
    }
}


Try to add this to your onDestroy method:

ImageView imageView = (ImageView) findViewById(R.id.full_screen_image);
BitmapDrawable bd = (BitmapDrawable)imageView.getDrawable();
bd.getBitmap().recycle();
imageView.setImageBitmap(null);

It will recycle the bitmap used inside your ImageView.


Consume less memory and downsample/resize(see documentation of BitmapOptions#inSampleSize) the picture.


Your application must be leaking context. That's usually the reason why application crashes after several orientation changes. Read this carefully http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html.


You could also use something like this:

        File picture = new File("path_to_image");
        if (picture.exists()) {
            ImageView imageView = (ImageView)findViewById(R.id.imageView);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;
            Bitmap myBitmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), options);
            imageView.setImageBitmap(myBitmap);
        }

Read the following link for more information about the BitmapFactory options (especially inSampleSize, which controls the degree of subsampling): http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜