packagecom.example.download;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// 定义正在运行的线程
private int threadRunning = 3;
// 线程开启的数量
private int threadNum = 3;
private EditText et_url;
// 进度条
private ProgressBar progressBar;
private TextView tv_pb;
private int currentProgress = 0;
private boolean flag = true;
// 记录进度条的值
public static int pb_count = 0;
public static Handler handler;
public static final int TEXTVALUE = 1;
public static int pb_num = 0;
public static int size = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取控件对象
et_url = (EditText) findViewById(R.id.et_url);
progressBar = (ProgressBar) findViewById(R.id.tv_jindu);
tv_pb = (TextView) findViewById(R.id.tv_pb);
File sdDir = Environment.getExternalStorageDirectory();
File pdFile = new File(sdDir, pb.txt);
InputStream is = null;
try {
if (pdFile.exists()) {
is = new FileInputStream(pdFile);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (is != null) {
String value = StreamTools.streamTostr(is);
String arr[] = value.split(;);
progressBar.setMax(Integer.valueOf(arr[0]));// 最大值
currentProgress = Integer.valueOf(arr[1]);// 当前值
progressBar.setProgress(currentProgress);
;
tv_pb.setText(当前的进度是 + arr[2] + %);
}
}
public void downLoadFile(View v) {
// 访问地址:
final String spec = et_url.getText().toString();// http://172.16.237.144:8080/Login/football.jpg;
if (TextUtils.isEmpty(spec)) {
Toast.makeText(this,
下载地址不能为空, Toast.LENGTH_LONG).show();
} else {
new Thread() {
public void run() {
try {
URL url = new URL(spec);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 设置请求的头文件信息还有时间
httpURLConnection.setRequestMethod(GET);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
if (httpURLConnection.getResponseCode() == 200) {
int fileLength = httpURLConnection
.getContentLength();
// 设置进度条的最大值
progressBar.setMax(fileLength);
// 判断你的设备SDCard是否可用
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 外部存储设备的路径
File sdfile = Environment
.getExternalStorageDirectory();
// 获取文件的名称
String fileName = spec.substring(spec
.lastIndexOf(/) + 1);
// 创建保存的文件
File file = new File(sdfile, fileName);
// 创建随机可以访问的文件对象
RandomAccessFile accessFile = new RandomAccessFile(
file, rwd);
// 设置文件大