2013-03-18 2 views
9

Я всегда находил следующий ответ на мой вопрос:Обновить галерею после удаления файла изображения?

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

но это не работает в моей системе (Nexus4 Android 4. ...)

Я могу создать файл и добавить его в Media-DB с этим кодом

Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
    Uri contentUri = Uri.fromFile(file); 
    mediaScanIntent.setData(contentUri); 
    context.sendBroadcast(mediaScanIntent); 

Где «файл» - это новый файл изображения, который я хочу добавить.

после удаления файла я пытаюсь refresch галереи по

Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED); 
    Uri contentUri = Uri.parse("file://" + Environment.getExternalStorageDirectory()); 
    intent.setData(contentUri); 
    context.sendBroadcast(intent); 

или

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

но есть еще пустой заполнитель в Galery.

Я не знаю, почему? ...

Чтобы быть на безопасной стороне я добавить слишком мою активность в AndroidManifest.xml

<intent-filter> 
      <action android:name="android.intent.action.MEDIA_MOUNTED" /> 
      <data android:scheme="file" /> 
     </intent-filter> 

, но результат тот же. Любая идея решить проблему?

+0

Возможные дубликат http://stackoverflow.com/questions/10716642/android-deleting-an-image –

ответ

6

Проверьте ниже фрагмент кода, чтобы проверить все случаи для добавления/удаления файлов изображений/перемещение программным и намекнуть галереи приложение, чтобы обновить данные

/*** 
* Refresh Gallery after add image file programmatically 
* Refresh Gallery after move image file programmatically 
* Refresh Gallery after delete image file programmatically 
* 
* @param fileUri : Image file path which add/move/delete from physical location 
*/ 
public void refreshGallery(String fileUri) { 

    // Convert to file Object 
    File file = new File(fileUri); 

    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { 
     // Write Kitkat version specific code for add entry to gallery database 
     // Check for file existence 
     if (file.exists()) { 
      // Add/Move File 
      Intent mediaScanIntent = new Intent(
        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
      Uri contentUri = Uri.fromFile(new File(fileUri)); 
      mediaScanIntent.setData(contentUri); 
      BaseApplication.appContext.sendBroadcast(mediaScanIntent); 
     } else { 
      // Delete File 
      try { 
       BaseApplication.appContext.getContentResolver().delete(
         MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
         MediaStore.Images.Media.DATA + "='" 
           + new File(fileUri).getPath() + "'", null); 
      } catch (Exception e) { 
       e.printStackTrace(); 

      } 
     } 
    } else { 
     BaseApplication.appContext.sendBroadcast(new Intent(
       Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" 
         + getBaseFolder().getAbsolutePath()))); 
    } 
} 
11

После KitKat вы не можете отправить Intent для запуска MediaScanner на всю память устройства, потому что это интенсивная задача с процессором I \ O, и если каждое приложение, загружающее изображение или удаляющее его, называет эту батарею намерения, которая легко истощается, поэтому они решили заблокировать эту операцию. Вот варианты:

Используйте старый способ для предварительной KitKat

Пройди свой Filepath:

if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { 
    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
       Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 
} else{ 


    MediaScannerConnection.scanFile(mContext, filePath, null, new MediaScannerConnection.OnScanCompletedListener() { 
     /* 
     * (non-Javadoc) 
     * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri) 
     */ 
     public void onScanCompleted(String path, Uri uri) 
     { 
     Log.i("ExternalStorage", "Scanned " + path + ":"); 
     Log.i("ExternalStorage", "-> uri=" + uri); 
     } 
    }); 

} 

Более надежный подход обновить MediaStore непосредственно:

// Set up the projection (we only need the ID) 
String[] projection = { MediaStore.Images.Media._ID }; 

// Match on the file path 
String selection = MediaStore.Images.Media.DATA + " = ?"; 
String[] selectionArgs = new String[] { file.getAbsolutePath() }; 

// Query for the ID of the media matching the file path 
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
ContentResolver contentResolver = getContentResolver(); 
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null); 
if (c.moveToFirst()) { 
    // We found the ID. Deleting the item via the content provider will also remove the file 
    long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID)); 
    Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id); 
    contentResolver.delete(deleteUri, null, null); 
} else { 
    // File not found in media store DB 
} 
c.close(); 
Смежные вопросы