保存后图像未反映在图库中

时间:2012-01-23 05:11:05

标签: javascript android json

 if (action.equals("saveToGallery")) {

                        JSONObject obj = args.getJSONObject(0);
                        String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null;
                        String imageName = obj.has("imageName") ? obj.getString("imageName") : null;
                        String savedImgSrc = saveImageToGallery(imageSource, imageName);
                        Log.v("SAve To Gallery ", "saved file url:  " + savedImgSrc);

                        return new PluginResult(PluginResult.Status.OK);
                    }
                    return new PluginResult(PluginResult.Status.INVALID_ACTION);
                } catch (JSONException e) {
                    e.printStackTrace();
                    return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
                }

public String saveImageToGallery(String imgSrc, String imgName) {
        Log.v("Save To Gallery ", "image SRc:  " + imgSrc + " , image Name:"
                + imgName);

        Context ctx = this.ctx;
        AssetManager assmgr = ctx.getAssets();
        File tempDir = new File("/sdcard/HarmonyDayApp/wallpapers/");
        tempDir.mkdirs();
        File file = new File(tempDir, imgName);
        try {
            InputStream is = null;
            is = assmgr.open("www/" + imgSrc);
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
            is.close();
            os.close();
        } catch (IOException ex) {
            Log.w("ExternalStorage", "Error writing " + file, ex);
        }
        return file.getAbsolutePath();

    }

这是我用来将图像保存到设备库的代码。但是,保存图像后,如果我检查图库,则图像不存在。它是在我重新加载应用程序或画廊之后的某个时间。对此问题的任何建议都会有所帮助。

2 个答案:

答案 0 :(得分:0)

您需要在保存图像后手动扫描媒体,方法是按照以下代码:

 // Tell the media scanner about the new file so that it is
    // immediately available to the user.
    MediaScannerConnection.scanFile(this,new String[] { file.toString() }, null,
    new MediaScannerConnection.OnScanCompletedListener() {
    public void onScanCompleted(String path, Uri uri) {
    Log.i("ExternalStorage", "Scanned " + path + ":");
    Log.i("ExternalStorage", "-> uri=" + uri);
    }
    });

答案 1 :(得分:0)

试试这个:

在图库中添加图片后,您需要广播

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(“file://”+
 Environment.getExternalStorageDirectory())));

希望它对你有用。 :)