2016-09-13 52 views
2

我正在嘗試使用標準相機應用拍攝照片並將其保存到僅可用於我的應用的存儲中。無法保存使用標準相機應用拍攝的照片

public void startCamera(View view) 
{ 
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) 
    { 
     File imageFile = null; 

     try 
     { 
      imageFile = createImageFile(); 
     } 
     catch (IOException ex) 
     { 
      ex.printStackTrace(); 
     } 

     if(imageFile != null) 
     { 
      Uri imageUri = FileProvider.getUriForFile(this, "vasiljevic.filip.secretnotes", imageFile); 
      takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
      startActivityForResult(takePictureIntent, 1); 
     } 
    } 
} 

createImageFile方法:

private File createImageFile() throws IOException 
{ 
    String timeStamp = new SimpleDateFormat("yyyyddMM_HHmmss").format(new Date()); 
    EditText editText = (EditText) findViewById(R.id.txtNoteName); 
    String noteName = editText.getText().toString(); 
    String imageFileName = noteName + "_" + timeStamp; 
    File storageDir = new File(getFilesDir(), "images"); 
    if(!storageDir.exists()) 
    { 
     storageDir.mkdir(); 
    } 

    File image = File.createTempFile(imageFileName, ".jpg", storageDir); 

    return image; 
} 

這是包含FileProvider清單的一部分:

<provider 
     android:authorities="vasiljevic.filip.secretnotes" 
     android:name="android.support.v4.content.FileProvider" 
     android:exported="false" 
     android:grantUriPermissions="true"> 
     <meta-data 
      android:name="android.support.FILE_PROVIDER_PATHS" 
      android:resource="@xml/file_paths" /> 
    </provider> 

而且file_paths.xml:

<paths xmlns:android="http://schemas.android.com/apk/res/android"> 
<files-path name="my_images" path="images/"/> 
</paths> 

我拍照後,它顯示混亂如果我在模擬器上運行它,或者「畫廊已經停止」,如果我在真實設備上運行它,年齡「攝像頭已停止」。後來,如果我嘗試使用ACTION_VIEW意圖訪問它,它會顯示「無法打開圖像」,如果我在真實設備上嘗試它,或者如果我在模擬器上嘗試它,它就像打開圖像一樣,但屏幕全是黑色並沒有顯示真實圖像。

我在做對吧?這段代碼是否應該正確保存圖像?它主要基於拍攝照片只是官方的Android教程:Taking photos simply

回答

2

FLAG_GRANT_WRITE_URI_PERMISSION添加到Intent。目前,您的第三方應用程序無權將照片保存到您的Uri

如果您支持的舊版Android 5.0以上,you might also need to use a ClipData workaround,因爲Intent標誌不影響舊版Android版本上的EXTRA_OUTPUT

+0

試過之前與該國旗,它沒有工作,我支持比5.0版本更舊的版本,所以我要檢查此ClipData解決方法,看看它是否工作,謝謝 – Seviel

+0

ClipData工作! – Seviel

相關問題