Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

Android How to use MediaScannerConnection scanFile

Im adding images to a folder on the SDCARD. Since the images and my folder is not immediately visible in the Gallery im trying to get the MediaScannerConnection to update and show the folder/images in the gallery. This is not working so good for me since nothing shows up in Gallery. Im only testing in Eclipse AVD.

I dont see much talk about this maybe because the scanFile is new since api8. Could someone show how this is done?

Im trying it in both a service and Activity but keep getting uri=null when onScanCompleted.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I realized that perhaps you were looking for a solution what would work previous to api level 8, and I could not make sense of Mitch's answer. I solved it by building a class for scanning a single file:

import java.io.File;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;

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();
    }

    @Override
    public void onMediaScannerConnected() {
        mMs.scanFile(mFile.getAbsolutePath(), null);
    }

    @Override
    public void onScanCompleted(String path, Uri uri) {
        mMs.disconnect();
    }

}

and you would use it like this to make the MediaScannerConnection scan a single file:

new SingleMediaScanner(this, file);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...