【问题标题】:How to use MediaScannerConnection scanFile?如何使用 MediaScannerConnection 扫描文件?
【发布时间】:2015-06-10 18:37:04
【问题描述】:

我正在将图像下载到 SDCARD 上的文件夹中。由于图像和我的文件夹在图库中不会立即可见,因此我试图让 MediaScannerConnection 更新并显示图库中的文件夹/图像。 向您展示如何在视图代码中执行此操作?

private void downloadImage() {
    if (future != null) {
        //set the callback and start downloading
        future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
            @Override
            public void onCompleted(Exception e, Response<InputStream> result) {
                boolean success = false;
                if (e == null && result != null && result.getResult() != null) {
                    try {
                        //prepare the file name
                        String url = mSelectedImage.getUrl();
                        String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
                        //create a temporary directory within the cache folder
                        File dir = Utils.getAlbumStorageDir("wall-tx");
                        //create the file
                        File file = new File(dir, fileName);
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        //copy the image onto this file
                        Utils.copyInputStreamToFile(result.getResult(), file);

                        //animate the first elements
                        animateCompleteFirst(true);

                        //Broadcast the Media Scanner Intent to trigger it

                        success = true;
                    } catch (Exception ex) {
                        Log.e("walltx", ex.toString());
                    }

                    //animate after complete
                    animateComplete(success);
                } else {
                    animateReset(true);
                }
            }
        });
    }
}

【问题讨论】:

    标签: java android


    【解决方案1】:
        MediaScannerConnection.scanFile(this, new String[]{file.getPath()},
                null, new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        // now visible in gallery
                    }
                });
    

    【讨论】:

    • 不要只转储代码块。包括 cmets 并解释其工作原理。
    • 代码自行解释,因为我使用了媒体扫描仪连接,它已经传递给我并且易于调试
    • 在某些情况下,例如动作处理程序,MainActivity.this&lt;ActivityClass&gt;.this 是比this 更好的选择,因为scanFile 的第一个参数是上下文,而不是回调类。
    猜你喜欢
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多