2015-10-15 77 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