我有imageView
的活动。当我旋转设备onCreate
开始在后台线程内创建位图时。经过几次旋转后,我在位图创建上有一个OutOfMemoryError
。
解决这个问题的正确方法是什么? weak references
是否有决定?
这是我的代码:
public class ImageActivity extends AppcompatActivity implements View.OnTouchListener {
private ImageView imageView;
private Disposable imageDisp;
@Override
public void onDestroy() {
imageDisp.dispose();
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
imageView = (ImageView) findViewById(R.id.main_imageview);
String source = getIntent().getStringExtra("source");
imageView.setImageBitmap(null);
imageView.setTag(source);
imageDisp = Observable.fromCallable(()->{
File outputFile = new File(source);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap b = BitmapFactory.decodeFile(outputFile.getPath(), options); // here I have a outOfMemory
outputFile.delete();
return b;
}).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(bitmap -> {
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(ImageActivity.this);
},
throwable -> Toast.makeText(this, String.valueOf(throwable.getMessage()), Toast.LENGTH_SHORT).show());
}
}
答案 0 :(得分:-1)
我不知道它是多么正确,但这有效:
imageDisp = Observable.fromCallable(()->{
System.gc();
final WeakReference<Bitmap> bitmapReference = new WeakReference<Bitmap>(BitmapFactory.decodeFile(outputFile.getPath(), options));
outputFile.delete();
return bitmapReference;
}).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(bitmap -> {
imageView.setImageBitmap(bitmap.get());
imageView.setOnTouchListener(ImageActivity.this);
},
throwable -> Toast.makeText(this, String.valueOf(throwable.getMessage()), Toast.LENGTH_SHORT).show());