有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java摄像头应用程序在按下后退按钮时保存空文件

我正在片段中使用一个摄像头应用程序。一切正常,拍摄的照片保存在我希望的地方

问题是,当我在照片应用程序中按下设备上的后退按钮时,会保存一张空图像。我怎样才能避免呢

这是我的CameraActivity

public class CameraActivity extends Activity {
    private static final String TAG = "CameraActivity";
    String currentFilePath;
    String currentFileName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new CameraTask().execute();
    }

    public void dispatchPictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                Toast.makeText(this, R.string.msg_picture_not_saved, Toast.LENGTH_LONG).show();
            }
            if (photoFile != null) {
                Uri photoUri = FileProvider.getUriForFile(this, getClass().getCanonicalName(), photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(takePictureIntent, Constants.REQUEST_TO_TAKE_PICTURE);

                addPictureToGallery();
                dispatchDataIntent();
            }
        }
    }

    public File createImageFile() throws IOException {
        File pathOfStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/Camera");
        pathOfStorageDir.mkdir();

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String filePrefix = "img_" + timeStamp + "_";
        String suffix = ".jpg";

        File image = File.createTempFile(filePrefix, suffix, pathOfStorageDir);
        currentFileName = image.getName();
        currentFilePath = image.getAbsolutePath();
        return image;
    }

    private void addPictureToGallery() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(currentFilePath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

    private void dispatchDataIntent() {
        Intent data = new Intent();
        data.putExtra(Constants.IMAGE_FILE_NAME, currentFileName);
        setResult(CameraActivity.RESULT_OK, data);
    }

    private class CameraTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            dispatchPictureIntent();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            finish();
        }
    }
}

谢谢你的帮助


共 (1) 个答案

  1. # 1 楼答案

    您的代码始终保存图像文件。如果用户按下后退按钮,尝试删除保存的图片。更好的方法是在检查结果代码之后将图像保存在onActivityResult

    public class CameraActivity extends Activity {
        private static final String TAG = "CameraActivity";
        String currentFilePath;
        String currentFileName;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            new CameraTask().execute();
        }
    
        public void dispatchPictureIntent() {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
    
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    Toast.makeText(this, R.string.msg_picture_not_saved, Toast.LENGTH_LONG).show();
                }
                if (photoFile != null) {
                    Uri photoUri = FileProvider.getUriForFile(this, getClass().getCanonicalName(), photoFile);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                    startActivityForResult(takePictureIntent, Constants.REQUEST_TO_TAKE_PICTURE);
    
                }
            }
        }
    
        public File createImageFile() throws IOException {
            File pathOfStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/Camera");
            pathOfStorageDir.mkdir();
    
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String filePrefix = "img_" + timeStamp + "_";
            String suffix = ".jpg";
    
            File image = File.createTempFile(filePrefix, suffix, pathOfStorageDir);
            currentFileName = image.getName();
            currentFilePath = image.getAbsolutePath();
            return image;
        }
    
        private void addPictureToGallery() {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            File f = new File(currentFilePath);
            Uri contentUri = Uri.fromFile(f);
            mediaScanIntent.setData(contentUri);
            this.sendBroadcast(mediaScanIntent);
        }
    
        private void dispatchDataIntent() {
            Intent data = new Intent();
            data.putExtra(Constants.IMAGE_FILE_NAME, currentFileName);
            setResult(CameraActivity.RESULT_OK, data);
        }
    
        private class CameraTask extends AsyncTask<Void, Void, Void> {
    
            @Override
            protected Void doInBackground(Void... params) {
                dispatchPictureIntent();
                return null;
            }
    
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
            }
        }
    
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == Constants.REQUEST_TO_TAKE_PICTURE){
                if(resultCode == RESULT_OK) {
    
                    addPictureToGallery();
                    dispatchDataIntent();
                } else {
                    File f = new File(currentFilePath);
                    f.delete();
                }
            }
                finish();
    
        }