下载图片文件更新图库工具类

来源:互联网 发布:华硕主板网络唤醒设置 编辑:程序博客网 时间:2024/05/16 09:07
public void downloadFile(final String url) {    AsyncHttpClient client = new AsyncHttpClient();    client.get(url, new AsyncHttpResponseHandler() {        @Override        public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] binaryData) {            try {                saveImg(url, binaryData);            } catch (IOException e) {                e.printStackTrace();            }        }        @Override        public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] binaryData, Throwable error) {            Toast.makeText(this, "下载失败",Toast.LENGTH_LONG).show();        }    });}public void saveImg(String url, byte[] bytes) throws IOException {    if (!isMounted()) return;    File dir = new File(CACHEDIR);    if (!dir.exists()) dir.mkdirs();    FileOutputStream fos = new FileOutputStream(new File(dir, getName(url)));    fos.write(bytes);    fos.close();    //更新图库    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);    Uri uri = Uri.fromFile(new File(dir, getName(url)));    intent.setData(uri);    sendBroadcast(intent);}public static boolean isMounted() {    return Environment.MEDIA_MOUNTED.equals(            Environment.getExternalStorageState());}public String getName(String url) {    return md5(url) + ".png";}public String md5(String stringContent) {    String ret = null;    if (stringContent != null) {        try {            MessageDigest digest = MessageDigest.getInstance("MD5");            byte[] data = digest.digest(stringContent.getBytes());            BigInteger bigInteger = new BigInteger(1, data);            ret = bigInteger.toString(16);        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        }    }    return ret;}
0 0