Android項目實戰(三十一):非同步下載apk檔案並安裝(非靜默安裝),androidapk

來源:互聯網
上載者:User

Android項目實戰(三十一):非同步下載apk檔案並安裝(非靜默安裝),androidapk

前言:

  實現非同步下載apk檔案 並 安裝。(進度條對話方塊顯示下載進度的展現方式)

  涉及技術點:

        1、ProgressDialog       進度條對話方塊  用於顯示下載進度

        2、AsyncTask             非同步任務的使用    耗時操作不能再主線程中進行      安卓開發_淺談AsyncTask

        3、File                       檔案相關操作    將檔案的位元組資料組建檔案

        4、自動開啟安裝應用操作       下載網路apk資料並組建檔案之後需要我們去執行這個apk的安裝操作(非靜默安裝)

   實現前提:

          1、我們下載的apk的url地址 

        2、檔案許可權,網路許可權    

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />     //檔案操作許可權    <uses-permission android:name="android.permission.INTERNET" />                  //網路許可權

 

----------------------------------------------------------------------------------------------------------------------------------------

實現:

1、建立ProgressDialog對象,初始化操作,開啟下載的非同步任務

   private void showDownloadProgressDialog(Context context) {        ProgressDialog progressDialog = new ProgressDialog(context);        progressDialog.setTitle("提示");        progressDialog.setMessage("正在下載...");        progressDialog.setIndeterminate(false);        progressDialog.setMax(100);        progressDialog.setCancelable(false);                    //設定不可點擊介面之外的地區讓對話方塊小時        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);         //進度條類型        progressDialog.show();        String downloadUrl = "http://ac-edNxPKqQ.clouddn.com/800exxxxxxx68ebcefda.apk"; //這裡寫你的apk url地址        new DownloadAPK(progressDialog).execute(downloadUrl);    }

 

2、下載apk的非同步任務

  首先看一下整個非同步任務的結構

private class DownloadAPK extends AsyncTask<String, Integer, String> {        ProgressDialog progressDialog;        File file;        public DownloadAPK(ProgressDialog progressDialog) {            this.progressDialog = progressDialog;        }        @Override        protected String doInBackground(String... params) {
       //根據url擷取網路資料產生apk檔案 return null; } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress);    // 這裡 改變ProgressDialog的進度值
    } @Override protected void onPostExecute(String s) { super.onPostExecute(s);
       //到這裡說明下載完成,判斷檔案是否存在,如果存在,執行安裝apk的操作 } }

  (1)、 局部變數

      ProgressDialog 用於顯示下載進度

      File                  根據網路資料產生的apk檔案

     ProgressDialog progressDialog;        File file;

  (2)、構造方法,將外部的ProgressDialog對象傳到非同步任務裡

      public DownloadAPK(ProgressDialog progressDialog) {            this.progressDialog = progressDialog;        }

  (3)、進度更新方法,將下載進度現在在對話方塊中

     @Override        protected void onProgressUpdate(Integer... progress) {            super.onProgressUpdate(progress);            progressDialog.setProgress(progress[0]);        }

  (4)、下載網路資料產生apk檔案的操作

     @Override        protected String doInBackground(String... params) {            URL url;            HttpURLConnection conn;            BufferedInputStream bis = null;            FileOutputStream fos = null;            try {                url = new URL(params[0]);                conn = (HttpURLConnection) url.openConnection();                conn.setRequestMethod("GET");                conn.setConnectTimeout(5000);                int fileLength = conn.getContentLength();                bis = new BufferedInputStream(conn.getInputStream());                String fileName = Environment.getExternalStorageDirectory().getPath() + "/magkare/action.apk";                file = new File(fileName);                if (!file.exists()) {                    if (!file.getParentFile().exists()) {                        file.getParentFile().mkdirs();                    }                    file.createNewFile();                }                fos = new FileOutputStream(file);                byte data[] = new byte[4 * 1024];                long total = 0;                int count;                while ((count = bis.read(data)) != -1) {                    total += count;                    publishProgress((int) (total * 100 / fileLength));                    fos.write(data, 0, count);                    fos.flush();                }                fos.flush();            } catch (IOException e) {                e.printStackTrace();            } finally {                try {                    if (fos != null) {                        fos.close();                    }                } catch (IOException e) {                    e.printStackTrace();                }                try {                    if (bis != null) {                        bis.close();                    }                } catch (IOException e) {                    e.printStackTrace();                }            }            return null;        }

  (5)、檔案下載完成後

         判斷檔案是否存在,存在的話要開啟安裝apk的操作,並關閉進度對話方塊

               不存在的話說明檔案下載失敗,進行相關提示即可

    @Override        protected void onPostExecute(String s) {            super.onPostExecute(s);            openFile(file);                 //開啟安裝apk檔案操作            progressDialog.dismiss();      //關閉對話方塊        }

  (6)、開啟apk檔案安裝apk的操作

    

     private void openFile(File file) {            if (file!=null){                Intent intent = new Intent(Intent.ACTION_VIEW);                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");                TaskListActivity.this.startActivity(intent);            }        }

 

完整代碼:

private void showDownloadProgressDialog(Context context) {        ProgressDialog progressDialog = new ProgressDialog(context);        progressDialog.setTitle("提示");        progressDialog.setMessage("正在下載...");        progressDialog.setIndeterminate(false);        progressDialog.setMax(100);        progressDialog.setCancelable(false);        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);        progressDialog.show();        String downloadUrl = "http://ac-edNxPKqQ.clouddn.com/80xxxxxxxebcefda.apk";        new DownloadAPK(progressDialog).execute(downloadUrl);    }    /**     * 下載APK的非同步任務     */    private class DownloadAPK extends AsyncTask<String, Integer, String> {        ProgressDialog progressDialog;        File file;        public DownloadAPK(ProgressDialog progressDialog) {            this.progressDialog = progressDialog;        }        @Override        protected String doInBackground(String... params) {            URL url;            HttpURLConnection conn;            BufferedInputStream bis = null;            FileOutputStream fos = null;            try {                url = new URL(params[0]);                conn = (HttpURLConnection) url.openConnection();                conn.setRequestMethod("GET");                conn.setConnectTimeout(5000);                int fileLength = conn.getContentLength();                bis = new BufferedInputStream(conn.getInputStream());                String fileName = Environment.getExternalStorageDirectory().getPath() + "/magkare/action.apk";                file = new File(fileName);                if (!file.exists()) {                    if (!file.getParentFile().exists()) {                        file.getParentFile().mkdirs();                    }                    file.createNewFile();                }                fos = new FileOutputStream(file);                byte data[] = new byte[4 * 1024];                long total = 0;                int count;                while ((count = bis.read(data)) != -1) {                    total += count;                    publishProgress((int) (total * 100 / fileLength));                    fos.write(data, 0, count);                    fos.flush();                }                fos.flush();            } catch (IOException e) {                e.printStackTrace();            } finally {                try {                    if (fos != null) {                        fos.close();                    }                } catch (IOException e) {                    e.printStackTrace();                }                try {                    if (bis != null) {                        bis.close();                    }                } catch (IOException e) {                    e.printStackTrace();                }            }            return null;        }        @Override        protected void onProgressUpdate(Integer... progress) {            super.onProgressUpdate(progress);            progressDialog.setProgress(progress[0]);        }        @Override        protected void onPostExecute(String s) {            super.onPostExecute(s);            openFile(file);            progressDialog.dismiss();        }        private void openFile(File file) {            if (file!=null){                Intent intent = new Intent(Intent.ACTION_VIEW);                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");                TaskListActivity.this.startActivity(intent);            }        }    }
非同步下載apk檔案並安裝

 

  

------------------------------------------------------------------------------------------------------------------------------------------

注意:

如果是一次性全部擷取到網路檔案的位元組資料,當檔案過大的時候會出現OOM的問題。

此方法 實現邊下載擷取網路檔案的位元組資料邊組建檔案的操作。   不用擔心OOM 的問題。 其他檔案下載操作都可以參考此方法。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.