NonJava
NonJava

Reputation: 45

How to use MediaScannerConnection scanFile?

I'm downloading image to a folder on the SDCARD. Since the images and my folder is not immediately visible in the Gallery I'm trying to get the MediaScannerConnection to update and show the folder/images in the gallery. Shows you how to do this in view code ?

private void downloadImage() {
    if (future != null) {
        //set the callback and start downloading
        future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
            @Override
            public void onCompleted(Exception e, Response<InputStream> result) {
                boolean success = false;
                if (e == null && result != null && result.getResult() != null) {
                    try {
                        //prepare the file name
                        String url = mSelectedImage.getUrl();
                        String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
                        //create a temporary directory within the cache folder
                        File dir = Utils.getAlbumStorageDir("wall-tx");
                        //create the file
                        File file = new File(dir, fileName);
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        //copy the image onto this file
                        Utils.copyInputStreamToFile(result.getResult(), file);

                        //animate the first elements
                        animateCompleteFirst(true);

                        //Broadcast the Media Scanner Intent to trigger it

                        success = true;
                    } catch (Exception ex) {
                        Log.e("walltx", ex.toString());
                    }

                    //animate after complete
                    animateComplete(success);
                } else {
                    animateReset(true);
                }
            }
        });
    }
}

Upvotes: 1

Views: 3574

Answers (1)

Mahmoud Zamel
Mahmoud Zamel

Reputation: 76

    MediaScannerConnection.scanFile(this, new String[]{file.getPath()},
            null, new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    // now visible in gallery
                }
            });

Upvotes: 5

Related Questions