是否有一种在运行时将新图像资源(从SD卡)添加到图库窗口小部件的好方法?
答案 0 :(得分:25)
“新形象资源”?
图像资源是.apk应用程序包中/ res / drawable文件夹的一部分。您无法在运行时添加“新”图像资源。
您还有其他一些用例吗?
海报解释后编辑:
您必须将媒体文件添加到Media Store才能被图库窗口小部件看到。使用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
。
答案 1 :(得分:1)
添加文件时向MediaStore Content Provider
发送广播
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" />