动态添加图片到图库小部件

8

有没有一种好的方法在运行时将新的图像资源(来自SD卡)添加到画廊小部件中?


你正在解析某个网站并想要动态添加图片吗? - Sankar Ganesh PMP
不完全是,只是从SD卡中读取。 - eyecreate
2个回答

28

"新的图像资源"?

图像资源是您的.apk应用程序包内/res/drawable文件夹的一部分。您无法在运行时添加"新的"图像资源。

您还有其他用例吗?

在张贴者的解释后进行编辑:

您必须将媒体文件添加到媒体存储库中,以便通过图库小部件看到它们。使用MediaScanner。我在我的代码中使用这个方便的包装器:

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
    }
}

然后实例化 MediaScannerWrapper 并使用 scan() 方法启动它。您可以对其进行调整,以同时处理多个文件。提示:传递文件路径的列表,然后循环遍历 mConnection.scanFile


是的,我在谈论存储在外部存储器上的图像。 - eyecreate
那么,这与画廊小部件如何连接以显示有关? - eyecreate
画廊小部件显示添加到媒体存储的所有文件。 - Peter Knego
2
不幸的是,这似乎不能更新使用该信息的应用程序...例如,下载mp3并运行此代码将扫描它,但不会添加到默认媒体播放器。要做到这一点,您需要按照此处描述的方式context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 刷新MediaStore on android. 参考链接: https://dev59.com/unA75IYBdhLWcg3wbofM - NoBugs

1

当您添加文件时,向MediaStore内容提供程序发送广播

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageAdded)));

在KitKat之前的设备上工作。
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
              Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

请注意this,同时适用于Lolipop系统,也可以解决KitKat系统的问题。

ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA,"file path");
values.put(MediaStore.Images.Media.MIME_TYPE,"image/jpeg");
mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);

添加权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接