class DownLoadImageService implements Runnable {
private String url;
private Context context;
private ImageDownLoadCallBack callBack;
public DownLoadImageService(Context context, String url, ImageDownLoadCallBack callBack) {
this.url = url;
this.callBack = callBack;
this.context = context;
}
@Override
public void run() {
File file = null;
try {
file = Glide.with(context)
.load(url)
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file != null) {
callBack.onDownLoadSuccess(file);
} else {
callBack.onDownLoadFailed();
}
}
}
}
/**
* 执行单线程列队执行
*/
public void runOnQueue(Runnable runnable) {
if (singleExecutor == null) {
singleExecutor = Executors.newSingleThreadExecutor();
}
singleExecutor.submit(runnable);
}
/**
* 启动图片下载线程
*/
private void onDownLoad() {
DownLoadImageService service = new DownLoadImageService(this, url, new ImageDownLoadCallBack() {
@Override
public void onDownLoadSuccess(File file) {
try {
int bytesum = 0;
int byteread = 0;
File imgfile = new File(savaPath); //Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yida"+url.substring(url.lastIndexOf("/"));我用的保存文件的地址
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = new FileOutputStream(imgfile);
byte[] buffer = new byte[1000];
int length;
while ( (byteread = inputStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
outputStream.write(buffer, 0, byteread);
}
outputStream.flush();
outputStream.close();
inputStream.close();
handle.sendEmptyMessageDelayed(0,0); //保存成功后采用handler发送消息到主线程。进行toast提示用户
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDownLoadFailed() {
}
});
//启动图片下载线程
runOnQueue(service);
}
private Handler handle = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
handle.removeMessages(0);
Toast.makeText(ZoomImageActivity.this, "保存成功,保存在yida文件夹下", Toast.LENGTH_SHORT).show();
mDialog.dismiss();
}
};

发表评论 取消回复