2014-02-17 41 views

回答

4

在大多數設備上,您只需稍等片刻即可自動檢測新照片。

如果你想瓶坯立即刷新到圖庫,您需要使用MediaScanner類,這將刷新畫廊 - 刪除刪除的照片,添加新的等等...

public void refreshGallery() { 
    Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
    String newPhotoPath = "file:" + image.getAbsolutePath(); // image is the created file image 
    File file = new File(newPhotoPath); 
    Uri contentUri = Uri.fromFile(file); 
    scanIntent.setData(contentUri); 
    sendBroadcast(scanIntent); 
} 

希望這有助於!

+0

改變'ACTION_MEDIA_MOUNTED'用'ACTION_MEDIA_SCANNER_SCAN_FILE'解決的問題。編輯你的答案,所以我接受這是正確的答案! –

+0

完成,謝謝!我已經學到了一些新的自己:-) – gilonm

+0

爲較老的android-s做這項工作?我有一臺android-4.2平板電腦,其中掃描單個文件不會工作,而其他android-4.4手機上的相同代碼工作。隨着android-4.2我可以開始掃描整個SD卡,但不是一個單一的文件。這是一個Android 4.2的問題或只是我的a-4.2平板電腦的問題? – k3b

0

確定了我的代碼,它爲我工作它給,我可以在Android圖庫查看所有圖片剛剛從該行

getallimages(Environment.getExternalStorageDirectory()); 

調用這個函數和我的函數低於

private void getallimages(File dir) 
    { 

       String[] STAR = { "*" }; 

     final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER; 
     Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy); 
     int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA); 
     int count = imagecursor.getCount(); 
     for (int i = 0; i < count; i++) { 
      imagecursor.moveToPosition(i); 
      int id = imagecursor.getInt(image_column_index); 
      ImageItem imageItem = new ImageItem(); 

      if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760) 
      { 
       imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA)); 

        imageItem.id = id; 
        imageItem.selection = false; //newly added item will be selected by default 
        controller.images.add(imageItem); 

      } 
} 

} 
0
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 

在'保存'代碼後插入這行代碼。

這將觸發媒體掃描,並且所有文件夾中的所有媒體文件('.nomedia'文件除外)將更新&可在圖庫中看到。

Source

MediaScanner Documentation

OR

// Tell the media scanner about the new file so that it is 
// immediately available to the user. 
MediaScannerConnection.scanFile(this, 
     new String[] { file.toString() }, null, 
     new MediaScannerConnection.OnScanCompletedListener() { 
    public void onScanCompleted(String path, Uri uri) { 
     Log.i("ExternalStorage", "Scanned " + path + ":"); 
     Log.i("ExternalStorage", "-> uri=" + uri); 
    } 
}); 

Google's Sample Code

+0

這是一個非常耗時的過程。我只想添加一個文件! –

+0

我不知道如何只需添加一個文件。您將不得不重新掃描整個文件系統,或等待android系統自動爲您完成。 –

+0

我添加了另一種方法,我發現在developers.android.com希望它可以幫助! –