Skip to content

Instantly share code, notes, and snippets.

@aftabsikander
Created June 20, 2018 14:27
Show Gist options
  • Select an option

  • Save aftabsikander/c547e1121a221bbb0356fc98a5b891b2 to your computer and use it in GitHub Desktop.

Select an option

Save aftabsikander/c547e1121a221bbb0356fc98a5b891b2 to your computer and use it in GitHub Desktop.

Revisions

  1. aftabsikander created this gist Jun 20, 2018.
    20 changes: 20 additions & 0 deletions ProjectUtils.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    public class ProjectUtils {
    /***
    * Force MediaScanner to update its media database for recently added files.
    * @param context the calling context.
    * @param filePathForScan File path which will request the media scanner to rescan and add it
    * to the media database.
    */
    public static void forceUpdateMediaScanner(Context context, String filePathForScan) {
    if (context != null) {
    new SingleMediaScanner(context, new File(filePathForScan));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
    Uri.parse("file://" + filePathForScan)));
    } else {
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
    Uri.parse("file://" + filePathForScan)));
    }
    }
    }
    }
    45 changes: 45 additions & 0 deletions SingleMediaScanner.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    import android.content.Context;
    import android.media.MediaScannerConnection;
    import android.media.MediaScannerConnection.MediaScannerConnectionClient;
    import android.net.Uri;

    import java.io.File;

    import timber.log.Timber;


    public class SingleMediaScanner implements MediaScannerConnectionClient {

    private MediaScannerConnection mMs;
    private File mFile;

    public SingleMediaScanner(Context context, File f) {
    mFile = f;
    mMs = new MediaScannerConnection(context, this);
    mMs.connect();
    }

    /**
    * Called to notify the client when a connection to the
    * MediaScanner service has been established.
    */
    @Override
    public void onMediaScannerConnected() {
    mMs.scanFile(mFile.getAbsolutePath(), null);
    }

    /**
    * Called to notify the client when the media scanner has finished
    * scanning a file.
    *
    * @param path the path to the file that has been scanned.
    * @param uri the Uri for the file if the scanning operation succeeded
    */
    @Override
    public void onScanCompleted(String path, Uri uri) {
    Timber.i("ExternalStorage" + " Scanned " + path + ":");
    Timber.i("ExternalStorage" + " -> uri=" + uri);
    mMs.disconnect();

    }
    }