多線程下載Apk并提示安裝
本項(xiàng)目是一個多線程下載應(yīng)用并提示是否安裝的小例子,從網(wǎng)上下載apk存儲到手機(jī)指定目錄,可以在通知欄顯示下載進(jìn)度進(jìn)度,下載完成后會有一個對話框提示用戶是否安裝,如果不需要可以刪除,項(xiàng)目有非常非常詳細(xì)的中文目錄,項(xiàng)目涉及知識:文件流、網(wǎng)絡(luò)下載鏈接協(xié)議、讀寫權(quán)限、Handler、Notification、跑馬燈。
源碼簡介
本項(xiàng)目是一個多線程下載應(yīng)用并提示是否安裝的小例子,從網(wǎng)上下載apk存儲到手機(jī)指定目錄,可以在通知欄顯示下載進(jìn)度進(jìn)度,下載完成后會有一個對話框提示用戶是否安裝,如果不需要可以刪除,項(xiàng)目有非常非常詳細(xì)的中文目錄,項(xiàng)目涉及知識:文件流、網(wǎng)絡(luò)下載鏈接協(xié)議、讀寫權(quán)限、Handler、Notification、跑馬燈。
源碼運(yùn)行截圖
源碼片段
- // 下載APK的線程匿名類START
- private Runnable mdownApkRunnable = new Runnable() {
- @Override
- public void run() {
- try {
- URL url = new URL(apkDownloadPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.connect();
- int length = conn.getContentLength();
- InputStream is = conn.getInputStream();
- File file = new File(savePath);
- Log.e("test", file.exists()+"");
- if (!file.exists()) {
- Log.e("test1", file.exists()+"");
- file.mkdir();
- Log.e("test2", file.exists()+"");
- }
- String apkFile = saveFileName;
- Log.e("test3", apkFile);
- File ApkFile = new File(apkFile);
- FileOutputStream fos = new FileOutputStream(ApkFile);
- int count = 0;
- byte buf[] = new byte[1024];
- do {
- int numread = is.read(buf);
- count += numread;
- progress = (int) (((float) count / length) * 100);
- if(handmsg < progress){
- handmsg ++;
- mHandler.sendEmptyMessage(DOWN_UPDATE);
- }
- // 更新進(jìn)度
- if (numread <= 0) {
- // 下載完成通知安裝
- mHandler.sendEmptyMessage(DOWN_OVER);
- break;
- }
- fos.write(buf, 0, numread);
- } while (true);// 點(diǎn)擊取消就停止下載.
- fos.close();
- is.close();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- Log.e("test", e.getMessage());
- }
- }
- };
源碼鏈接:http://down.51cto.com/data/1968727
責(zé)任編輯:chenqingxiang
來源:
網(wǎng)絡(luò)整理