需要知識
讀取網(wǎng)絡(luò)下載文件的指定范圍的字節(jié)
RandomAccessFile支持跳到文件任意位置讀寫數(shù)據(jù)
3. 記得添加和開啟權(quán)限
4. 高版本無法連接http網(wǎng)絡(luò)解決方案
具體代碼
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.開啟下載服務(wù)
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","文件創(chuàng)建成功與否:" + mkdir);
}
Log.e("zhy",dir.getAbsolutePath());
// 創(chuàng)建本地文件
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 :數(shù)據(jù)需要保存到本地悦污。
return;
}
raf.write(buffer,0,length);
threadInfo.setFinished(threadInfo.getFinished() + length);
Log.e("zhy","線程" + threadInfo.getId() + "的下載進度 == " + threadInfo.getFinished());
}
// 標識線程執(zhí)行完畢
isFinished = true;
// 檢查下載任務(wù)是否完成
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","下載完成");
}
}
}
}``