此文,仅做为个人学习Android,记录成长以及方便复习!
使用线程池分成3个线程下载
首先从界面下手,使用一个下载按钮,和一个TexTView,点击按钮开始下载,下载完成在TextView提示完成
创建一个类,里面包含一个内部类,内部类实现下载!
其中,通过for来实现分别给线程定义开始和结束位置
for(int i=0;i<3;i++){ long strat = i*block;//设置起始位置 long end = (i+1)*block-1;//设置结束位置 //第三个线程把剩余的都添加进去 //例如总长度是10,第一个线程1-3,第二个拿4-6,剩下的就只能都给线程三了也就是7-10 if(i==2){ end=count; }
package com.example.qqazl001.download;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class Download {
private Handler handler;
public Download(Handler handler){
this.handler = handler;
}
//创建线程池,里面包含三个线程
private Executor threadPool = Executors.newFixedThreadPool(3);
//线程下载的内部类
static class DownLoadRunnable implements Runnable{
private String url;//下载的链接
private String fileName;//文件路径
private long start; //起始位置
private long end; //结束位置
private Handler handler;
public DownLoadRunnable(String url,String fileName,long start,long end,Handler handler){
this.url = url;
this.fileName= fileName;
this.start = start;
this.end = end;
this.handler = handler;
}
@Override
public void run() {
//获取链接
URL httpUrl = null;
try {
httpUrl = new URL(url);
//打开链接
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
//设置请求长度
conn.setRequestProperty("Range","bytes="+start+"-"+end);
conn.setRequestMethod("GET");//设置发送方式
conn.setReadTimeout(5000);//设置超时时间
//写入本地,指定文件名和可读可写
RandomAccessFile access = new RandomAccessFile(new File(fileName),"rwd");
access.seek(start);//从起始位置开始写
InputStream is = conn.getInputStream();//获取输入流
byte[] b = new byte[1024*4];//设置缓冲空间
int len = 0;
while((len = is.read(b))!=-1){ //每次读取 1024*4个字节,不为-1则持续读取
access.write(b,0,len); //写入文件
}
//释放资源
if(access!=null){
access.close();
}
if(is!=null){
is.close();
}
//下载完成之后,创建Message,设置what为1并发送给Handler
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void downLoadFile(String url){
try {
//获取链接
URL httpUrl = new URL(url);
//打开链接
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
conn.setRequestMethod("GET");//设置发送方式
conn.setReadTimeout(5000);//设置超时时间
int count = conn.getContentLength(); //获取长度
int block = count/3; //总长度分别给3个线程的长度
String fileName = getFileName(url);//获取文件名
//获取SD卡根目录
File parent = Environment.getExternalStorageDirectory();
//创建文件
File fileDownLoad = new File(parent,fileName);
for(int i=0;i<3;i++){
long strat = i*block;//设置起始位置
long end = (i+1)*block-1;//设置结束位置
//第三个线程把剩余的都添加进去
//例如总长度是10,第一个线程1-3,第二个拿4-6,剩下的就只能都给线程三了也就是7-10
if(i==2){
end=count;
}
//fileDownLoad.getAbsolutePath() 获取绝对路径
DownLoadRunnable runnable = new DownLoadRunnable(url,fileDownLoad.getAbsolutePath(),strat,end,handler);
//加入线程池
threadPool.execute(runnable);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//文件名是url最后一个“/”后面加1的位置到结束
public String getFileName(String url){
return url.substring(url.lastIndexOf("/")+1);
}
}
在Acitivy调用类,并传入参数
package com.example.qqazl001.download;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button bt1;
private TextView tv1;
private int count=0;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
int result = msg.what;
count+=result;
if(count==3){
tv1.setText("下载完成!");
}
}
};
//android 6.0之上的系统除了添加权限还要在你报错的代码前面添加请求权限的代码。
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE };
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = findViewById(R.id.tv1);
bt1 = findViewById(R.id.bt1);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
verifyStoragePermissions(MainActivity.this);
new Thread(){
@Override
public void run() {
Download download = new Download(handler);
download.downLoadFile("http://pic162.nipic.com/file/20180425/10185515_143945322000_2.jpg");
}
}.start();
}
});
}
}
注意的是:6.0开始不止要在清单文件(AnddroidManifest.xml)添加内存读写权限还需要动态调用
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" tools:ignore="ProtectedPermissions" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET">uses-permission>
//android 6.0之上的系统除了添加权限还要在你报错的代码前面添加请求权限的代码。 private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; public static void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); } }