【问题标题】:dynamically add pictures to gallery widget将图片动态添加到图库小部件
【发布时间】:2011-05-08 15:33:20
【问题描述】:

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

【问题讨论】:

  • 您是否正在解析任何网站并希望动态添加图片?
  • 不完全是,只是来自 SD 卡。

标签: android


【解决方案1】:

“新的图片资源”?

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

您还有其他用例吗?

海报解释后编辑:

您必须将媒体文件添加到媒体商店才能被图库小部件看到。使用媒体扫描仪。我在我的代码中使用了这个方便的包装器:

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

【讨论】:

  • 是的,我说的是存储在外部存储上的图像。
  • 那么,它如何连接到画廊小部件以显示?
  • 图库小部件显示添加到媒体商店的所有文件。
  • 不幸的是,这似乎没有更新使用该信息的应用程序...例如,下载 mp3 并运行此代码将扫描它,但不会添加到默认媒体播放器。为此,您需要 context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));如此处所述:stackoverflow.com/questions/3300137/…
【解决方案2】:

添加文件时向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" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-16
    • 2011-01-10
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    相关资源
    最近更新 更多