我是Android开发人员的开始,作为一个练习项目,我正在尝试制作和活动,可以拍照,将其保存到外部存储,并在ImageView中显示。几乎所有东西似乎都在工作,但是,我似乎有内存泄漏。
当屏幕方向改变时,我相信活动被破坏,然后重新创建。为了继续显示图像,我将图像的路径存储为onSaveInstanceState中的包中的字符串,并在onResotreInstanceState中重置图像。拍摄5mp照片,我可以旋转一次屏幕,然后在第二次旋转时,应用程序崩溃,LogCat报告内存不足错误。使用较低分辨率的图像,我获得更多旋转,但应用程序仍然最终崩溃,我得到相同的错误。
我一直在阅读关于android内存泄漏的内容,而且似乎所有内容似乎都没有使用静态Drawables,它可以引用视图,并阻止vm释放内存。据我所知,我没有做任何类似的事情来继续保持参考。如果有人能帮助我找到我的错误,我真的很感激。这是代码:
public class CameraTestsActivity extends Activity {
private Uri fileUri;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void takePicture(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputImageFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 0);
}
private static Uri getOutputImageFileUri() {
return Uri.fromFile(getOutputImageFile());
}
private static File getOutputImageFile(){
Log.d("CameraTestsActivity", "Storage state: " + Environment.getExternalStorageState());
if (Environment.getExternalStorageState().equals("mounted")){
File mediaStorageDirs = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures" + "/CameraTestsActivity");
if (! mediaStorageDirs.exists()){
if (! mediaStorageDirs.mkdirs()){
Log.d("CameraTestsActivity", "Failed to create directories");
mediaStorageDirs = null;
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File imageFile = new File(mediaStorageDirs.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
mediaStorageDirs = null;
return imageFile;
}
Log.d("CameraTestsActivity", "Storage state bad");
return null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK){
if (requestCode == 0){
setImage();
}
}
else{
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
fileUri = Uri.parse(savedInstanceState.getString("uri"));
setImage();
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("uri", fileUri.toString());
super.onSaveInstanceState(outState);
}
private void setImage(){
ImageView image = (ImageView)findViewById(R.id.imageView1);
File file = new File(fileUri.toString().substring(7));
if (!file.exists())
Log.d("CameraTestsActivity", "File " + fileUri.toString().substring(7) + "does not exist");
image.setImageURI(fileUri);
}
}
答案 0 :(得分:1)
在显示位图时,我们应该注意它的大小不超过堆大小或说VM预算。 虽然您没有任何内存泄漏,但是当您更改方向时,可能需要一些时间来清理以前加载的位图,以免出现内存溢出错误。 要避免此错误,请阅读此How to display bitmap efficiently
答案 1 :(得分:0)