android下载进度条

AsyncTask是个不错的东西,可以使用它来做下载进度条。代码讲解如下:

Java代码
package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class DownloadFile extends Activity {

public static final String LOG_TAG = "test";

private ProgressDialog mProgressDialog;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;


File rootDir = Environment.getExternalStorageDirectory();

//定义要下载的文件名
public String fileName = "test.jpg";
public String fileURL = "https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG";

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("Android Download File With Progress Bar");

//检查下载目录是否存在
checkAndCreateDirectory("/mydownloads");

//执行asynctask
new DownloadFileAsync().execute(fileURL);
}


class DownloadFileAsync extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}


@Override
protected String doInBackground(String... aurl) {

try {
//连接地址
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

//计算文件长度
int lenghtOfFile = c.getContentLength();


FileOutputStream f = new FileOutputStream(new File(rootDir + "/my_downloads/", fileName));

InputStream in = c.getInputStream();

//下载的代码
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;

while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();

} catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}

return null;
}

protected void onProgressUpdate(String... progress) {
Log.d(LOG_TAG,progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}


public void checkAndCreateDirectory(String dirName){
File new_dir = new File( rootDir + dirName );
if( !new_dir.exists() ){
new_dir.mkdirs();
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
}

package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class DownloadFile extends Activity {

public static final String LOG_TAG = "test";

private ProgressDialog mProgressDialog;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;


File rootDir = Environment.getExternalStorageDirectory();

//定义要下载的文件名
public String fileName = "test.jpg";
public String fileURL = "https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG";

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("Android Download File With Progress Bar");

//检查下载目录是否存在
checkAndCreateDirectory("/mydownloads");

//执行asynctask
new DownloadFileAsync().execute(fileURL);
}


class DownloadFileAsync extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}


@Override
protected String doInBackground(String... aurl) {

try {
//连接地址
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

//计算文件长度
int lenghtOfFile = c.getContentLength();


FileOutputStream f = new FileOutputStream(new File(rootDir + "/my_downloads/", fileName));

InputStream in = c.getInputStream();

//下载的代码
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;

while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();

} catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}

return null;
}

protected void onProgressUpdate(String... progress) {
Log.d(LOG_TAG,progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}


public void checkAndCreateDirectory(String dirName){
File new_dir = new File( rootDir + dirName );
if( !new_dir.exists() ){
new_dir.mkdirs();
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
}


配置文件

注意打开文件保存权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadfile"
android:versionCode="1"
android:versionName="1.0">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-sdk android:minSdkVersion="4" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".DownloadFile"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
</manifest>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值