有没有一种好的方法在运行时将新的图像资源(来自SD卡)添加到画廊小部件中?
有没有一种好的方法在运行时将新的图像资源(来自SD卡)添加到画廊小部件中?
"新的图像资源"?
图像资源是您的.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
。
当您添加文件时,向MediaStore内容提供程序
发送广播
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageAdded)));
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" />