Android ACTION_IMAGE_CAPTURE Intent

后端 未结 14 2001
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 02:04

We are trying to use the native camera app to let the user take a new picture. It works just fine if we leave out the EXTRA_OUTPUT extra and returns the small B

14条回答
  •  心在旅途
    2020-11-22 03:00

    I know this has been answered before but I know a lot of people get tripped up on this, so I'm going to add a comment.

    I had this exact same problem happen on my Nexus One. This was from the file not existing on the disk before the camera app started. Therefore, I made sure that the file existing before started the camera app. Here's some sample code that I used:

    String storageState = Environment.getExternalStorageState();
            if(storageState.equals(Environment.MEDIA_MOUNTED)) {
    
                String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + MainActivity.this.getPackageName() + "/files/" + md5(upc) + ".jpg";
                _photoFile = new File(path);
                try {
                    if(_photoFile.exists() == false) {
                        _photoFile.getParentFile().mkdirs();
                        _photoFile.createNewFile();
                    }
    
                } catch (IOException e) {
                    Log.e(TAG, "Could not create file.", e);
                }
                Log.i(TAG, path);
    
                _fileUri = Uri.fromFile(_photoFile);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
                intent.putExtra( MediaStore.EXTRA_OUTPUT, _fileUri);
                startActivityForResult(intent, TAKE_PICTURE);
            }   else {
                new AlertDialog.Builder(MainActivity.this)
                .setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
                .setCancelable(true).create().show();
            }
    

    I first create a unique (somewhat) file name using an MD5 hash and put it into the appropriate folder. I then check to see if it exists (shouldn't, but its good practice to check anyway). If it does not exist, I get the parent dir (a folder) and create the folder hierarchy up to it (therefore if the folders leading up to the location of the file don't exist, they will after this line. Then after that I create the file. Once the file is created I get the Uri and pass it to the intent and then the OK button works as expected and all is golden.

    Now,when the Ok button is pressed on the camera app, the file will be present in the given location. In this example it would be /sdcard/Android/data/com.example.myapp/files/234asdioue23498ad.jpg

    There is no need to copy the file in the "onActivityResult" as posted above.

提交回复
热议问题