dynamically add pictures to gallery widget

前端 未结 2 1972
萌比男神i
萌比男神i 2020-12-06 07:38

Is there a good way to add new image resources(from SD card) to a gallery widget at runtime?

2条回答
  •  孤街浪徒
    2020-12-06 08:03

    "new image resources"?

    Image resources are a part of /res/drawable folder inside your .apk application package. You can not add "new" image resources during runtime.

    Is there some other use case you had in mind?

    Edited after posters explanation:

    You have to add media files to Media Store in order to be seen by gallery widget. Use MediaScanner. I use this convenient wrapper in my code:

    public class MediaScannerWrapper implements  
    MediaScannerConnection.MediaScannerConnectionClient {
        private MediaScannerConnection mConnection;
        private String mPath;
        private String mMimeType;
    
        // filePath - where to scan; 
        // mime type of media to scan i.e. "image/jpeg". 
        // use "*/*" for any media
        public MediaScannerWrapper(Context ctx, String filePath, String mime){
            mPath = filePath;
            mMimeType = mime;
            mConnection = new MediaScannerConnection(ctx, this);
        }
    
        // do the scanning
        public void scan() {
            mConnection.connect();
        }
    
        // start the scan when scanner is ready
        public void onMediaScannerConnected() {
            mConnection.scanFile(mPath, mMimeType);
            Log.w("MediaScannerWrapper", "media file scanned: " + mPath);
        }
    
        public void onScanCompleted(String path, Uri uri) {
            // when scan is completes, update media file tags
        }
    }
    

    Then instantiate MediaScannerWrapper and start it with scan(). You could tweak it to handle more than one file at the time. Hint: pass List of File paths, and then loop around mConnection.scanFile.

提交回复
热议问题