我是一名初级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);
}
}