需要知识
读取网络下载文件的指定范围的字节
RandomAccessFile支持跳到文件任意位置读写数据
3. 记得添加和开启权限
具体代码
1.开始和暂停下载
// 开始下载
private void startDown(){
Intent intent = new Intent(getActivity(), DownService.class);
intent.setAction(DownService.ACTION_START);
intent.putExtra("downUrl","https://download.java.net/openjdk/jdk9/ri/openjdk-9_src.zip");
getActivity().startService(intent);
}
// 暂停下载
private void stopDown(){
Intent intent = new Intent(getActivity(),DownService.class);
intent.setAction(DownService.ACTIOn_STOP);
getActivity().startService(intent);
}
2.开启下载服务
public class DownService extends Service {
private static final String TAG = "DownService";
public static final String ACTION_START = "ACTION_START";
public static final String ACTIOn_STOP = "ACTION_PAUSE";
public static final String DOWN_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/dahai/";
public static final String DOWN_FILE_NAME = "aaa.zip";
private String downUrl;
private DownTask mDownTask;
private int length;
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if (action.equals(ACTION_START)) {
downUrl = intent.getStringExtra("downUrl");
new InitThread().start();
} else if (action.equals(ACTIOn_STOP)) {
Log.e(TAG,"停止下载");
mDownTask.pause = true;
}
return super.onStartCommand(intent, flags, startId);
}
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Log.e("zhy","开始下载");
if (mDownTask == null)
mDownTask = new DownTask(new File(DOWN_PATH,DOWN_FILE_NAME),downUrl,length);
mDownTask.startDown();
return true;
}
});
class InitThread extends Thread {
HttpURLConnection connection;
RandomAccessFile raf;
@Override
public void run() {
try {
URL url = new URL(downUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 获取文件长度
length = connection.getContentLength();
Log.e("zhy","文件的长度 == " + length);
}
if (length < 0) {
return;
}
File dir = new File(DOWN_PATH);
if (!dir.exists()) {
boolean mkdir = dir.mkdir();
Log.e("zhy","文件创建成功与否:" + mkdir);
}
Log.e("zhy",dir.getAbsolutePath());
// 创建本地文件
File file = new File(DOWN_PATH,DOWN_FILE_NAME);
raf = new RandomAccessFile(file,"rwd");
raf.setLength(length);
handler.obtainMessage(1).sendToTarget();
}catch(MalformedURLException e){
e.printStackTrace();
Log.e("zhy",e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("zhy",e.toString());
}
}
}
}
3.具体下载控制代码
public class DownTask {
private long startPos;
private File downPath;
private String downUrl;
private long fileLength;
// todo : 线程安全。。。。
public boolean pause = false;
public static ExecutorService executorService = Executors.newCachedThreadPool();
List<ThreadInfo> threadInfos = new ArrayList<>();
private List<DownThread> mThreadList = null;
public DownTask(File downPath,String downUrl,long fileLength) {
this.downPath = downPath;
this.downUrl = downUrl;
this.fileLength = fileLength;
}
public void startDown() {
Log.e("zhy","开启下载线程");
pause = false;
if (threadInfos.size() == 0) {
long length = fileLength/3;
for (int i = 0;i < 3;i++) {
ThreadInfo threadInfo = new ThreadInfo(i,i * length,(i+1) * length -1,0);
if (i + 1 == 3) {
threadInfo.setEnd(fileLength);
}
threadInfos.add(threadInfo);
}
}
mThreadList = new ArrayList<>();
for (ThreadInfo threadInfo : threadInfos) {
DownThread t = new DownThread(threadInfo);
executorService.execute(t);
mThreadList.add(t);
}
}
class DownThread extends Thread {
private ThreadInfo threadInfo;
private boolean isFinished;
public DownThread(ThreadInfo threadInfo) {
this.threadInfo = threadInfo;
}
@Override
public void run() {
InputStream is;
RandomAccessFile raf;
try {
URL url = new URL(downUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
long start = threadInfo.getStart() + threadInfo.getFinished();
urlConnection.setRequestProperty("Range","bytes=" + start + "-" + threadInfo.getEnd());
raf = new RandomAccessFile(downPath, "rwd");
raf.seek(startPos);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_PARTIAL) {
is = urlConnection.getInputStream();
byte[] buffer = new byte[4096];
int length = -1;
while ((length = is.read(buffer)) != -1) {
if (pause) {
// todo :数据需要保存到本地。
return;
}
raf.write(buffer,0,length);
threadInfo.setFinished(threadInfo.getFinished() + length);
Log.e("zhy","线程" + threadInfo.getId() + "的下载进度 == " + threadInfo.getFinished());
}
// 标识线程执行完毕
isFinished = true;
// 检查下载任务是否完成
checkAllThreadFinished();
is.close();
raf.close();
urlConnection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void checkAllThreadFinished(){
synchronized (this) {
boolean allFinished = true;
for (DownThread thread : mThreadList) {
if (!thread.isFinished) {
allFinished = false;
break;
}
}
if (allFinished) {
Log.e("zhy","下载完成");
}
}
}
}``