多線程下載Apk并提示安裝
本項目是一個多線程下載應用并提示是否安裝的小例子,從網上下載apk存儲到手機指定目錄,可以在通知欄顯示下載進度進度,下載完成后會有一個對話框提示用戶是否安裝,如果不需要可以刪除,項目有非常非常詳細的中文目錄,項目涉及知識:文件流、網絡下載鏈接協議、讀寫權限、Handler、Notification、跑馬燈。
源碼簡介
本項目是一個多線程下載應用并提示是否安裝的小例子,從網上下載apk存儲到手機指定目錄,可以在通知欄顯示下載進度進度,下載完成后會有一個對話框提示用戶是否安裝,如果不需要可以刪除,項目有非常非常詳細的中文目錄,項目涉及知識:文件流、網絡下載鏈接協議、讀寫權限、Handler、Notification、跑馬燈。
源碼運行截圖
源碼片段
- // 下載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);
- }
- // 更新進度
- if (numread <= 0) {
- // 下載完成通知安裝
- mHandler.sendEmptyMessage(DOWN_OVER);
- break;
- }
- fos.write(buf, 0, numread);
- } while (true);// 點擊取消就停止下載.
- 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
責任編輯:chenqingxiang
來源:
網絡整理