如何添加媒体提供商?

时间:2015-06-10 09:52:21

标签: java android

当我下载图像并将其保存到Android设备时,图像不会出现在图库中,稍后手机重新启动后图像会显示在图库中。

以下是我下载图像并将其保存到设备的代码:

 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);

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

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

Utils.java

/**
 * http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file
 *
 * @param file
 * @return
 * @throws IOException
 */
public static String readFile(File file)
        throws IOException {
    return new Scanner(file, "UTF-8").useDelimiter("\\A").next();
}

/**
 * http://developer.android.com/training/basics/data-storage/files.html
 *
 * @param albumName
 * @return
 */

public static File getAlbumStorageDir(String albumName) {
    // Get the directory for the user's public pictures directory.
    boolean success = false;
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName);
    if (!file.exists()) {
        success = file.mkdir();
    }
    if (!success)
        Log.i("wall-tx", "Directory not created");
    else
        Log.i("wall-tx", "Directory created");
    return file;
}
/**
 * http://developer.android.com/training/basics/data-storage/files.html
 *
 * @return
 */
public static boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

0 个答案:

没有答案