1
所以我是繼Android的教程捕捉(帶攝像頭的意圖)簡單安卓:保存到getExternalPublicStorageDirectory和畫廊顯示
在它說具體使用時getExternalStoragePublicDirectory調用(創建映像「文件」)的教程保存圖片,但在他們的例子中,他們使用getExternalStorageDirectory。基本上它是一個「盡我所能不像我所做」的例子。
所以我嘗試使用getExternalStoragePublicDirectory出現各種錯誤。我最終得到它的工作,我可以看到這些文件確實通過ADB shell存在。對我而言,我無法讓他們出現在畫廊中。使用媒體掃描器連接掃描文件似乎沒有辦法。有誰知道如何讓文件出現在畫廊中?
代碼片段:
private File createImageFile() throws IOException { // Create an image file name
String timeStamp = new
SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File pictureDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
// if the file does not exist, then create the file.
if(!pictureDir.exists())
{
pictureDir.mkdirs();
}
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
pictureDir /* directory */
);
boolean exists = image.exists();
this.currentPhotoPath = image.getAbsolutePath();
// Save a file: path for use with ACTION_VIEW intents
return image;
}
private void dispatchTakePictureIntent()
{
verifyStoragePermissions(this);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// i believe this is checking if the activity exists.
if(takePictureIntent.resolveActivity(getPackageManager()) != null)
{
File imageFile = null;
try
{
imageFile = createImageFile();
}
catch (IOException e)
{
Log.i("sf", e.getMessage());
Log.i("sf",e.getCause().getMessage());
}
if(imageFile != null)
{
imageFile.toURI();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageFile.toURI());
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private void addGalleryPic() throws IOException {
Intent mediaScanIntent = new
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(this.currentPhotoPath);
if(f.exists())
{
Log.i("sdf", f.getAbsolutePath() + " exists");
}
MediaScannerConnection.scanFile(this,
new String[]{currentPhotoPath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
String p = uri.getPath();
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
「使用媒體掃描儀連接掃描文件似乎沒有辦法」 - 它應該。但是,我沒有看到你在調用'addGalleryPic()'。 – CommonsWare
我沒有包含它,因爲它會假設我在onActivityResult覆蓋中做了這個。 @CommonsWare – j209
那麼也許'currentPhotoPath'是'null',因爲我沒有看到你如何將它保存在保存的實例狀態'Bundle'中,並且當攝像頭應用處於前景時,你的過程可能會被終止。 – CommonsWare