android实现文件下载
public void downImage(final String urls,final String name) {
direct = new File(Environment.getExternalStorageDirectory()
+ "/MyDowns");
if (!direct.exists()) {
direct.mkdirs();
}
new Thread(new Runnable() {
@Override
public void run() {
file = new File(Environment.getExternalStorageDirectory()+"/MyDowns/"+name+".png");
InputStream is = null;
try {
is = new URL(urls).openConnection().getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int len = is.read(bytes);
while (len>0){
fos.write(bytes,0,len);
len = is.read(bytes);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
----------------------------------------------------------
public long file_download(String uRl, String name) {
DownloadManager dm;
Toast.makeText(this.getApplication(), "正在下载 " + name,
Toast.LENGTH_LONG).show();
File direct = new File(Environment.getExternalStorageDirectory()
+ "/MyDowns");
if (!direct.exists()) {
direct.mkdirs();
}
dm = (DownloadManager) this.getApplication().getApplicationContext().getSystemService
(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setVisibleInDownloadsUi(true);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setVisibleInDownloadsUi(true)
.setTitle(name)
.setDescription(name)
.setDestinationInExternalPublicDir("/MyDowns", name + ".png");
long refernece = dm.enqueue(request);
return refernece;
}
-------------------------------------
public void get(String urlimage,String name) {
File dirs = new File(Environment.getExternalStorageDirectory()+"/myImage/");
if(!dirs.exists()){
dirs.mkdirs();
}
File file = new File(dirs+"/"+name+".png");
HttpUtils http = new HttpUtils();
HttpHandler handler = http.download(urlimage,
file.toString(),
true,
true,
new RequestCallBack<File>() {
@Override
public void onStart() {
Log.e("Start ", "Start");
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
Log.e("Loading ", "" + current + "/" + total);
}
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
Log.e("Success ", "" + responseInfo.result.getPath());
}
@Override
public void onFailure(HttpException error, String msg) {
Log.e("Failure ", "" + msg);
}
});
}