public class MainActivity extends Activity {
// 声明控件
// 路径与线程数量
private EditText et_url,et_num;
// 进度条
public static Progressbar pb_thread;
// 显示进度的 *** 作
private TextVIEw tv_pb;
// 线程的数量
public static int threadNum = 3;
// 每个线程负责下载的大小
public int blockSize;
public static int threadCount;// 数量
// 访问的path
public String path;
public static 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_path);
et_num = (EditText) findVIEwByID(R.ID.et_threadNum);
pb_thread = (Progressbar) findVIEwByID(R.ID.pb_down);
tv_pb = (TextVIEw) findVIEwByID(R.ID.tv_pb);
handler = new Handler() {
@OverrIDe
public voID handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case TEXTVALUE:
System.out.println("-----------------------"
+ MainActivity.pb_count + "//////"
+ MainActivity.size);
// 改变TEXTVIEw
pb_num = (MainActivity.pb_count * 100) / MainActivity.size;
tv_pb.setText("当前进度是+" + pb_num + "%");
break;
default:
break;
}
}
};
}
@OverrIDe
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.down,menu);
return true;
}
//下载 *** 作
public voID downLoad(VIEw v) {
// 改变变量值:
MainActivity.flag = true;
MainActivity.pb_count = 0;
path = et_url.getText().toString();
String threadNum_et = et_num.getText().toString();
if (TextUtils.isEmpty(path) || TextUtils.isEmpty(threadNum_et)) {
Toast.makeText(this,"不能为空",Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(this,"url:" + path + "--" + threadNum_et,
Toast.LENGTH_LONG).show();
// 转换成数字
threadNum = Integer.valueOf(threadNum_et);
new Thread(new Runnable() {
@OverrIDe
public voID run() {
try {
// 创建出URL对象
URL url = new URL(path);
// 创建出 httpURLConnection对象
httpURLConnection httpURLConnection = (httpURLConnection) url
.openConnection();
// 设置 发请求发送的方式
httpURLConnection.setRequestMethod("GET");
// 设置请求是否超时时间
httpURLConnection.setConnectTimeout(5000);
// 设置
httpURLConnection
.setRequestProperty("User-Agent",
" Mozilla/5.0 (compatible; MSIE 10.0; windows NT 6.2; TrIDent/6.0)");
// 是否响应成功
if (httpURLConnection.getResponseCode() == 200) {
// 获取文件的大小
size = httpURLConnection.getContentLength();
System.out.println("文件的大小" + size);
// 设置进度条的最大值
pb_thread.setMax(size);
// 创建文件 //保存到SD卡上
// 首先判断是否拥有sdcard
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 获取sdCard文件目录对象
file sdfile = Environment
.getExternalStorageDirectory();
// 创建文件对象
file file = new file(sdfile,"youdao.exe");
RandomAccessfile accessfile = new RandomAccessfile(
file,"rwd");
// 设置文件的大小
accessfile.setLength(size);
// 每个线程下载的大小
blockSize = size / threadNum;
// 开三个线程 *** 作此文件
for (int i = 1; i <= threadNum; i++) {
// 1 2 3
// 计算出每个线程开始的位置
int startSize = (i - 1) * blockSize;
// 结束位置
int endSize = (i) * blockSize;
// 当线程是最后一个线程的时候
if (i == threadNum) {
// 判断文件的大小是否大于计算出来的结束位置
if (size > endSize) {
// 结束位置 等于 文件的大小
endSize = size;
}
}
// 为每个线程创建一个随机的读取
RandomAccessfile threadAccessfile = new RandomAccessfile(
file,"rwd");
new Thread(new DownLoadThread(i,
threadAccessfile,startSize,endSize,
path)).start();
}
}
}
} catch (MalformedURLException e) {
// Todo auto-generated catch block
e.printstacktrace();
} catch (IOException e) {
// Todo auto-generated catch block
e.printstacktrace();
}
}
}).start();
}
//暂停 *** 作
public voID downPause(VIEw v) {
Toast.makeText(this,"暂停",Toast.LENGTH_LONG).show();
this.flag = false;
}
}
复制代码 代码如下:
public class DownLoadThread implements Runnable {
// 下载文件的封装
public RandomAccessfile accessfile;
// 线程下载文件的起始位置
public int startSize;
public int endSize;
// 文件下载的path路径
public String path;
public int threadID; // 线程的标识
public DownLoadThread(int threadID,RandomAccessfile accessfile,
int startSize,int endSize,String path) {
this.threadID = threadID;
this.accessfile = accessfile;
this.startSize = startSize;
this.endSize = endSize;
this.path = path;
}
@OverrIDe
public voID run() {
// 执行run方法
try {
// 创建文件到SD卡上去
// 首先判断是否拥有sdcard
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 获取sdCard文件目录对象
file sdfile = Environment.getExternalStorageDirectory();
file threadfile = new file(sdfile,threadID + ".txt");
if (threadfile.exists()) {
// 读取该文件的内容
// 创建文件的输入流对象
fileinputStream fis = new fileinputStream(threadfile);
// 采用工具类读取
byte data[] = StreamTools.isToData(fis);
// 转化成字符串
String threadLen = new String(data);
if ((threadLen != null) && (!"".equals(threadLen))) {
startSize = Integer.valueOf(threadLen);
// 解决 416BUG的错误
if (startSize > endSize) {
startSize = endSize - 1;
}
}
}
// 创建文件
// 创建URL对象
URL url = new URL(path);
// 创建httpURLConnection对象
httpURLConnection httpURLConnection = (httpURLConnection) url
.openConnection();
// 设置请求的头
httpURLConnection.setRequestMethod("GET");
// 设置请求是否超时时间
httpURLConnection.setConnectTimeout(5000);
// 设置
httpURLConnection
.setRequestProperty("User-Agent",
" Mozilla/5.0 (compatible; MSIE 10.0; windows NT 6.2; TrIDent/6.0)");
// 关键的设置
httpURLConnection.setRequestProperty("Range","bytes="
+ startSize + "-" + endSize);
// 输出当前线程
System.out.println("当前线程" + threadID + " 下载开始位置:" + startSize
+ " 下载结束位置:" + endSize);
// 响应成功
// 设置随机读取文件的 开始位置
accessfile.seek(startSize);
// 获取相应流对象
inputStream is = httpURLConnection.getinputStream();
// 创建输出流对象
byte buffer[] = new byte[1024];
int len = 0;
int threadTotal = 0;// 每个线程下载后保存记录 /
while ((len = is.read(buffer)) != -1) {
accessfile.write(buffer,len);
threadTotal += len;// 记录你写入的长度 //xml文件
//改变进度条:
setProgressbar(len);
// 通过文件记录文件下载的长度
fileOutputStream fos = new fileOutputStream(threadfile);
fos.write((threadTotal + "").getBytes());
fos.flush();
fos.close();
//发送handler消息
MainActivity.handler.sendEmptyMessage(MainActivity.TEXTVALUE);
if(!MainActivity.flag){
return;
}
}
accessfile.close();
is.close();
System.out.println(threadID + "线程执行完毕");
// 线程 *** 作
synchronized (MainActivity.class) {
MainActivity.threadCount++;
if (MainActivity.threadCount >= MainActivity.threadNum) {
for (int i = 1; i <= MainActivity.threadNum; i++) {
// 获取sdCard上的文件
file deletefile = new file(sdfile,i + ".txt");
if (deletefile.exists()) {
// 文件删除
deletefile.delete();
}
}
}
}
}
} catch (MalformedURLException e) {
// Todo auto-generated catch block
e.printstacktrace();
} catch (IOException e) {
// Todo auto-generated catch block
e.printstacktrace();
}
}
public synchronized voID setProgressbar(int len){
MainActivity.pb_count+=len;
MainActivity.pb_thread.setProgress(MainActivity.pb_count);
}
}
复制代码 代码如下:
public class StreamTools {
public static byte[] isToData(inputStream is) throws IOException{
// 字节输出流
ByteArrayOutputStream bops = new ByteArrayOutputStream();
// 读取数据的缓存区
byte buffer[] = new byte[1024];
// 读取长度的记录
int len = 0;
// 循环读取
while ((len = is.read(buffer)) != -1) {
bops.write(buffer,len);
}
// 把读取的内容转换成byte数组
byte data[] = bops.toByteArray();
bops.flush();
bops.close();
is.close();
return data;
}
}
完整源码 总结
以上是内存溢出为你收集整理的android中多线程下载实例全部内容,希望文章能够帮你解决android中多线程下载实例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)