2015-10-15 73 views
0

我使用的代码从开发者的网站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; 
    } 

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

回答

0

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

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

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

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

+0

表兄弟姐妹,当我浏览到该文件夹​​与文件管理的任何与没有文件,我认为没有文件。它与媒体扫描器无关 – Piet

+0

@Piet文件管理器,或者如果您连接到PC,在扫描之前不会显示新创建的文件。另外,尝试从代码本身获取文件并查看文件是否存在。 – Henry