android 下载文件 并显示下载进度
private String fileSavePath=Environment.getExternalStorageDirectory() + "/";//保存文件的本地路径
private String fileDownLoad_path="";//下载的URL
private String mfileName="";//下载的文件名字
private boolean mIsCancel = false;
private int mProgress;
private ProgressBar mProgressBar;
private Dialog mDownloadDialog;
private static final int DOWNLOADING = 1;
private static final int DOWNLOAD_FINISH = 2;
private Handler mUpdateProgressHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWNLOADING:
// 设置进度条
mProgressBar.setProgress(mProgress);
break;
case DOWNLOAD_FINISH:
// 隐藏当前下载对话框
mDownloadDialog.dismiss();
}
}
};
/**
* 显示正在下载的对话框
*/
protected void showDownloadDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("下载中");
View view = LayoutInflater.from(context).inflate(R.layout.dialog_progress, null);
mProgressBar = (ProgressBar) view.findViewById(R.id.id_progress);
builder.setView(view);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 隐藏当前对话框
dialog.dismiss();
// 设置下载状态为取消
mIsCancel = true;
}
});
mDownloadDialog = builder.create();
mDownloadDialog.show();
// 下载文件
downloadFile();
}
写下载 放在线程中
private void downloadFile() {
new Thread(new Runnable() {
@Override
public void run() {
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File dir = new File(fileSavePath);
if (!dir.exists()){
dir.mkdirs();
}
// 下载文件
HttpURLConnection conn = (HttpURLConnection) new URL(fileDownLoad_path).openConnection();
conn.connect();
InputStream is = conn.getInputStream();
int length = conn.getContentLength();
File apkFile = new File(fileSavePath, mfileName);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
byte[] buffer = new byte[1024];
while (!mIsCancel) {
int numread = is.read(buffer);
count += numread;
// 计算进度条当前位置
mProgress = (int) (((float) count / length) * 100);
// 更新进度条
mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);
// 下载完成
if (numread < 0) {
mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
fos.write(buffer, 0, numread);
}
fos.close();
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
dialogprogress的布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity" >
<ProgressBar
android:id="@+id/id_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
应该不缺少文件了。注意权限问题。
本文介绍如何在Android中实现文件下载,并在下载过程中显示进度条。内容涉及将下载操作放在后台线程中,使用DialogProgress布局更新进度,并提醒读者注意处理权限问题。
1070

被折叠的 条评论
为什么被折叠?



