自己封装了个下载工具类,包括有进度条和无进度条~
public class DownLoadUtils {
//无进度条下载
public static void downLoadFile(Context context, String httpUrl, final String fileName) {
int fileSize;
// TODO Auto-generated method stub
File tmpFile = new File("/sdcard/update");
if (!tmpFile.exists()) {
tmpFile.mkdir();
}
final File file = new File("/sdcard/update/" + fileName);
try {
URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
conn.connect();
double count = 0;
fileSize = conn.getContentLength();//文件大小
//判断内存是否够用
long sdFreeSize = SDCardUtils.getSDFreeSize() * 1024 * 1024;
Log.i("ruin", "剩余内存大小-- " + sdFreeSize);
if (sdFreeSize < fileSize) {
Toast.makeText(context, "您的内存不足", Toast.LENGTH_SHORT).show();
return;
}
if (conn.getResponseCode() >= 400) {
Toast.makeText(context, "连接超时", Toast.LENGTH_SHORT).show();
} else {
while (count <= 100) {
if (is != null) {
int numRead = is.read(buf);
if (numRead <= 0) {
break;
} else {
fos.write(buf, 0, numRead);
}
} else {
break;
}
}
Log.i("ruin", "文件下载成功");
}
conn.disconnect();
fos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//有进度条下载
public static void downLoadFile(Context context, String httpUrl, final String fileName, ShowProgress showProgress) {
int progress = 0;
int downLoadFileSize = 0;
showProgress.show(progress);
int fileSize;
// TODO Auto-generated method stub
File tmpFile = new File("/sdcard/Pictures");
if (!tmpFile.exists()) {
tmpFile.mkdir();
}
final File file = new File("/sdcard/Pictures/" + fileName);
try {
URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
conn.connect();
double count = 0;
fileSize = conn.getContentLength();//文件大小
//判断内存是否够用
long sdFreeSize = SDCardUtils.getSDFreeSize() * 1024 * 1024;
Log.i("ruin", "剩余内存大小-- " + sdFreeSize);
if (sdFreeSize < fileSize) {
Toast.makeText(context, "您的内存不足", Toast.LENGTH_SHORT).show();
return;
}
if (conn.getResponseCode() >= 400) {
Toast.makeText(context, "连接超时", Toast.LENGTH_SHORT).show();
} else {
while (count <= 100) {
if (is != null) {
int numRead = is.read(buf);
if (numRead <= 0) {
break;
} else {
downLoadFileSize += numRead;
progress = downLoadFileSize * 100 / fileSize;
showProgress.change(progress);
fos.write(buf, 0, numRead);
}
} else {
break;
}
}
showProgress.dismiss();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
Log.i("ruin", "文件下载成功");
}
conn.disconnect();
fos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public interface ShowProgress {
void show(int progress);//显示进度条
void change(int progress);//更新进度条
void dismiss();//隐藏进度条
}
}