照片通过意图不起作用

时间:2015-10-15 17:42:57

标签: android

我使用开发者网站https://developer.android.com/training/camera/photobasics.html

中的代码
btnPhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Log.d("Button", "take photo");
                dispatchTakePictureIntent();
            }
        });
    }
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        Log.d("storageDir",storageDir.toString());
        //File storageDir = "/Android/data/" + getApplicationContext().getPackageName() + "/files/";
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        return image;
    }

如果按下按钮,意图开始,我可以拍照,相机关闭但没有拍照(任何文件夹中没有照片)。我不知道为什么,代码应该有用。

1 个答案:

答案 0 :(得分:0)

您是如何得出图片文件夹中没有文件的结论?在Android中创建任何新文件时,它不会立即反映出来。要使其反映在图库中,您需要通过MediaScannerConnection进行扫描。

MediaScannerConnection.scanFile(getActivity(), new String[]{image.toString()}, null, null);

但如果情况并非如此:在你的onActivityResult()中,查询你收到的意图对象,看看你是否有你拍摄的图像的位图。

我希望这会有所帮助:capturing images with MediaStore.ACTION_IMAGE_CAPTURE intent in android