編輯:Android 開發實例
多執行緒下載的核心思路其實並不複雜:透過 HTTP 的 Range 屬性把檔案切成數段,各自交由獨立執行緒下載,再用 RandomAccessFile 隨機寫入同一個檔案的對應位置,最終自然合併為完整檔案。這樣既能充分利用頻寬,也能即時掌握下載進度。
建立名為 ThreadDemo 的工程後,我們先規劃使用者介面。布局檔 threaddemo.xml 包含下載網址、執行緒數輸入框、進度條、進度文字與開始下載按鈕:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下載地址"
- />
- <TextView
- android:id="@+id/downloadurl"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:lines="5"
- />
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="線程數"
- />
- <EditText
- android:id="@+id/downloadnum"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <ProgressBar
- android:id="@+id/downloadProgressBar"
- android:layout_width="fill_parent"
- style="?android:attr/progressBarStyleHorizontal"
- android:layout_height="wrap_content"
- />
- <TextView
- android:id="@+id/downloadinfo"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下載進度 0"
- />
- <Button
- android:id="@+id/downloadbutton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="開始下載"
- />
- </LinearLayout>
主界面負責初始化各元件、在按下按鈕時建立下載目錄並啟動下載執行緒,同時透過 Handler 把背景進度回傳到 UI 執行緒更新進度條:
- public class ThreadDownloadDemo extends Activity {
- private TextView downloadurl;
- private EditText downloadnum;
- private Button downloadbutton;
- private ProgressBar downloadProgressBar;
- private TextView downloadinfo;
- private int downloadedSize = 0;
- private int fileSize = 0;
- private long downloadtime;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.threaddemo);
- downloadurl = (TextView) findViewById(R.id.downloadurl);
- downloadurl.setText("https://file16.top100.cn/201105110911/AA5CC27CBE34DEB50A194581D1300881/Special_323149/%E8%8D%B7%E5%A1%98%E6%9C%88%E8%89%B2.mp3");
- downloadnum = (EditText) findViewById(R.id.downloadnum);
- downloadinfo = (TextView) findViewById(R.id.downloadinfo);
- downloadbutton = (Button) findViewById(R.id.downloadbutton);
- downloadProgressBar = (ProgressBar) findViewById(R.id.downloadProgressBar);
- downloadProgressBar.setVisibility(View.VISIBLE);
- downloadProgressBar.setMax(100);
- downloadProgressBar.setProgress(0);
- downloadbutton.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- download();
- downloadtime = SystemClock.currentThreadTimeMillis();
- }
- });
- }
- private void download() {
- // 獲取SD卡目錄
- String dowloadDir = Environment.getExternalStorageDirectory()
- + "/threaddemodownload/";
- File file = new File(dowloadDir);
- //創建下載目錄
- if (!file.exists()) {
- file.mkdirs();
- }
- //讀取下載線程數,如果為空,則單線程下載
- int downloadTN = Integer.valueOf("".equals(downloadnum.getText()
- .toString()) ? "1": downloadnum.getText().toString());
- String fileName = "hetang.mp3";
- //開始下載前把下載按鈕設置為不可用
- downloadbutton.setClickable(false);
- //進度條設為0
- downloadProgressBar.setProgress(0);
- //啟動文件下載線程
- new downloadTask("https://file16.top100.cn/201105110911/AA5CC27CBE34DEB50A194581D1300881/Special_323149/%E8%8D%B7%E5%A1%98%E6%9C%88%E8%89%B2.mp3", Integer
- .valueOf(downloadTN), dowloadDir + fileName).start();
- }
- Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- //當收到更新視圖消息時,計算已完成下載百分比,同時更新進度條信息
- int progress = (Double.valueOf((downloadedSize * 1.0 / fileSize * 100))).intValue();
- if (progress == 100) {
- downloadbutton.setClickable(true);
- downloadinfo.setText("下載完成!");
- Dialog mdialog = new AlertDialog.Builder(ThreadDownloadDemo.this)
- .setTitle("提示信息")
- .setMessage("下載完成,總用時為:"+(SystemClock.currentThreadTimeMillis()-downloadtime)+"毫秒")
- .setNegativeButton("確定", new DialogInterface.OnClickListener(){
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- })
- .create();
- mdialog.show();
- }else {
- downloadinfo.setText("當前進度:" + progress + "%");
- }
- downloadProgressBar.setProgress(progress);
- }
- };
- public class downloadTask extends Thread {
- private int blockSize, downloadSizeMore;
- private int threadNum = 5;
- String urlStr, threadNo, fileName;
- public downloadTask(String urlStr, int threadNum, String fileName) {
- this.urlStr = urlStr;
- this.threadNum = threadNum;
- this.fileName = fileName;
- }
- @Override
- public void run() {
- FileDownloadThread[] fds = new FileDownloadThread[threadNum];
- try {
- URL url = new URL(urlStr);
- URLConnection conn = url.openConnection();
- //防止返回-1
- InputStream in = conn.getInputStream();
- //獲取下載文件的總大小
- fileSize = conn.getContentLength();
- Log.i("bb", "======================fileSize:"+fileSize);
- //計算每個線程要下載的數據量
- blockSize = fileSize / threadNum;
- // 解決整除後百分比計算誤差
- downloadSizeMore = (fileSize % threadNum);
- File file = new File(fileName);
- for (int i = 0; i < threadNum; i++) {
- Log.i("bb", "======================i:"+i);
- //啟動線程,分別下載自己需要下載的部分
- FileDownloadThread fdt = new FileDownloadThread(url, file, i * blockSize, (i + 1) * blockSize - 1);
- fdt.setName("Thread" + i);
- fdt.start();
- fds[i] = fdt;
- }
- boolean finished = false;
- while (!finished) {
- // 先把整除的余數搞定
- downloadedSize = downloadSizeMore;
- finished = true;
- for (int i = 0; i < fds.length; i++) {
- downloadedSize += fds[i].getDownloadSize();
- if (!fds[i].isFinished()) {
- finished = false;
- }
- }
- handler.sendEmptyMessage(0);
- //線程暫停一秒
- sleep(1000);
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
這裡的重點是:先取得檔案總大小,除以執行緒數算出每段 block 大小,再為每段啟動一個 FileDownloadThread 各自下載,並用 downloadSizeMore 補上整除後的餘數,避免進度計算誤差。
每個下載執行緒透過 Range 標頭指定自己負責的位元組區間,並以 RandomAccessFile 的 seek 定位寫入點,同時即時記錄已下載量:
- public class FileDownloadThread extends Thread{
- private static final int BUFFER_SIZE=1024;
- private URL url;
- private File file;
- private int startPosition;
- private int endPosition;
- private int curPosition;
- //標識當前線程是否下載完成
- private boolean finished=false;
- private int downloadSize=0;
- public FileDownloadThread(URL url,File file,int startPosition,int endPosition){
- this.url=url;
- this.file=file;
- this.startPosition=startPosition;
- this.curPosition=startPosition;
- this.endPosition=endPosition;
- }
- @Override
- public void run() {
- BufferedInputStream bis = null;
- RandomAccessFile fos = null;
- byte[] buf = new byte[BUFFER_SIZE];
- URLConnection con = null;
- try {
- con = url.openConnection();
- con.setAllowUserInteraction(true);
- //設置當前線程下載的起止點
- con.setRequestProperty("Range", "bytes=" + startPosition + "-" + endPosition);
- Log.i("bb", Thread.currentThread().getName()+" bytes=" + startPosition + "-" + endPosition);
- //使用java中的RandomAccessFile 對文件進行隨機讀寫操作
- fos = new RandomAccessFile(file, "rw");
- //設置寫文件的起始位置
- fos.seek(startPosition);
- bis = new BufferedInputStream(con.getInputStream());
- //開始循環以流的形式讀寫文件
- while (curPosition < endPosition) {
- int len = bis.read(buf, 0, BUFFER_SIZE);
- if (len == -1) {
- break;
- }
- fos.write(buf, 0, len);
- curPosition = curPosition + len;
- if (curPosition > endPosition) {
- downloadSize+=len - (curPosition - endPosition) + 1;
- } else {
- downloadSize+=len;
- }
- }
- //下載完成設為true
- this.finished = true;
- bis.close();
- fos.close();
- }catch (IOException e) {
- e.printStackTrace();
- }
- }
- public boolean isFinished(){
- return finished;
- }
- public int getDownloadSize() {
- return downloadSize;
- }
- }
由於涉及網路連線與 SD 卡寫入,別忘了在 AndroidManifest.xml 中加上相應權限:
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Android MediaPlayer 音訊播放實戰
Android 提供了多種控制音訊與影片播放的方式,不論是播放本機檔案或串流來源都能應付,而其中最典型的做法就是使用 MediaPlayer 類別。 Android 透過
Android WebView 支持 HTML5 Video 全屏播放的關鍵配置與代碼
讓 WebView 裡的 video 標籤能正常播放,需要硬件加速;讓它能全屏,需要攔截 WebChromeClient 的兩個回調。這兩步聽起來簡單,但中間有幾個容易讓
Android記事本範例剖析(三):Activity生命週期與自訂控制項
本篇是 Android 記事本範例系列的第三篇,重點放在 Activity 生命週期與自訂控制項。透過實際切換畫面並觀察 Logcat,可以更清楚理解 Android 如
Android 端如何解析 JSON:以天氣查詢 App 為例
行動應用要顯示即時資訊,幾乎都得向伺服器要資料,而回傳格式十之八九是 JSON。它源自 JavaScript 的物件語法,但早已是語言中立的文字格式,任何平台都能讀。相比