26.Android 下载图片保存到相册
前言
有遇到没有这样的一种需求:浏览的大图后,点击保存下载高清原图到相册的需求。
现在的图片缓存大多都是Universal-Imager-Loader为多。但是我们在公司的某些离谱的需求(圈子系的需求,要求每条动态展示的图片不止6张,有一条30多张,直接报了Universal-Imager-Loader的OOM,怎么改配置都不能解决)上,后来调研了Glide
和Fresco
,发现Glide基本是完虐的节奏。
这里给大家提一个Glide小问题:Glide自带能把图片加载成圆角,Glide加载本地图片不能实现圆角。
实现思路
- 1.自定义一个AsyncTask下载图片
- 2.自定义一个Dialog显示下载进度
- 3.自定义一个Handler刷新Dialog的进度
- 4.下载完成后,保存图片到相册里
自定义Dialog
dialog_progressbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:padding="10dip" />
<TextView
android:id="@+id/load_info_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="正在提交..."
android:textColor="#000000" />
</LinearLayout>
CustomProgressBarDialog
/**
* 自定义进度条Dialog
*/
public class CustomProgressBarDialog extends Dialog {
private LayoutInflater mInflater;
private Context mContext;
private WindowManager.LayoutParams params;
private View mView;
private TextView promptTV;
public CustomProgressBarDialog(Context context) {
super(context);
this.init(context);
}
public CustomProgressBarDialog(Context context, int themeResId) {
super(context, themeResId);
this.init(context);
}
protected CustomProgressBarDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
this.init(context);
}
private void init(Context context) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.mContext = context;
this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mView = this.mInflater.inflate(R.layout.dialog_progressbar, null);
setContentView(this.mView);
// 设置window属性
this.params = getWindow().getAttributes();
this.params.gravity = Gravity.CENTER;
// 去背景遮盖
this.params.dimAmount = 0;
this.params.alpha = 1.0f;
// 不能关掉
this.setCancelable(false);
this.getWindow().setAttributes(this.params);
this.promptTV = (TextView) findViewById(R.id.load_info_text);
}
/**
* 设置内容
*
* @param prompt
*/
public void setLoadPrompt(String prompt) {
this.promptTV.setText(prompt);
}
}
自定义Handler
注意:这里可以参考Handler 通用模板。
private static final int HANDLER_LOADING = 262;
/**
* 刷新Dialog显示的进度Handler
*/
private static class LoadingHandler extends Handler {
private final WeakReference<DownloadImageToGalleryActivity> mActivity;
public LoadingHandler(DownloadImageToGalleryActivity activity) {
mActivity = new WeakReference<>(activity);
}
/**
* Subclasses must implement this to receive messages.
*
* @param msg
*/
@Override
public void handleMessage(Message msg) {
DownloadImageToGalleryActivity activity = this.mActivity.get();
if (activit