新增功能:進度條顯示更新進度

1.把下載和查詢下載進度的方法分開

//服務器中APK下載地址
    private String updateurl;
    private Context context;
// 下載應用的進度條
    private ProgressDialog mProgressDialog;
//下載唯一ID
    private long refernece;
    private DownloadManager downloadManager;
    /**
     * 從服務器中下載APK
     */
    private void downLoadApk() {
        if (TextUtils.isEmpty(updateurl)) {
            return;
        }
        try {
            String serviceString = Context.DOWNLOAD_SERVICE;
            context = this.getApplicationContext();
            downloadManager = (DownloadManager) context.getSystemService(serviceString);
            //將下載地址url放入uri中
            Uri uri = Uri.parse(updateurl);
            DownloadManager.Request request = new DownloadManager.Request(uri);
            request.allowScanningByMediaScanner();
            request.setVisibleInDownloadsUi(true);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setMimeType("application/vnd.android.package-archive");
            //文件如果存在,則刪除原來文件
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/app-debug/", "app-debug.apk");
            if (file.exists()) {
                file.delete();
            }         request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath() + "/app-debug/", "app-debug.apk");
            //獲得唯一下載id
            refernece = downloadManager.enqueue(request);
            //將id放進Intent
            Intent localIntent = new Intent(BROADCAST_ACTION);
            localIntent.putExtra(EXTENDED_DATA_STATUS, refernece);
        } catch (Exception exception) {
            Toast.makeText(getApplicationContext(), "下載新版本失敗", Toast.LENGTH_SHORT).show();
            loginMain();
        }
    }
/**
     * 查詢下載狀態
     */
private void searchStatus(){
        String serviceString = Context.DOWNLOAD_SERVICE;
        context = this.getApplicationContext();
        downloadManager = (DownloadManager) context.getSystemService(serviceString);
            //查詢下載信息
            DownloadManager.Query query=new DownloadManager.Query();
            query.setFilterById(refernece);
            try{
                boolean isGoging=true;
                while(isGoging){
                    Cursor cursor = downloadManager.query(query);
                    if (cursor != null && cursor.moveToFirst()) {
                        //獲取當前下載量
                        long downloadedBytes = cursor.getLong(
                                cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        long totalBytes = cursor.getLong(
                                cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                        mProgressDialog.setMax(((int) (totalBytes / 1024)));
                        int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                        switch(status){
                            case DownloadManager.STATUS_RUNNING:
                                mProgressDialog.setProgress(((int) (downloadedBytes / 1024)));
                                if(!mProgressDialog.isShowing()){
                                    mProgressDialog.show();
                                }
                                break;
                            //如果下載狀態為成功
                            case DownloadManager.STATUS_SUCCESSFUL:
                                isGoging=false;
                                mProgressDialog.dismiss();
                                installApkDialog();
                             case DownloadManager.STATUS_FAILED:
                                isGoging = false;
                                Toast.makeText(getApplicationContext(), "下載新版本失敗",  Toast.LENGTH_SHORT).show();
                                loginMain();
                                break;
                            case DownloadManager.STATUS_PAUSED:
                                searchReason();
                                break;
                        }
                    }

                    if(cursor!=null){
                        cursor.close();
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
    }

2.顯示進度條

/**
     * 下載進度顯示
     */
    private void getProgressDialog() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressNumberFormat("%1d KB/%2d KB");
        mProgressDialog.setMessage("正在更新...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//水平進度條
        mProgressDialog.setCancelable(true);//設置是否可以通過點擊Back鍵取消
        mProgressDialog.show();
        new Thread(){
            public void run(){
                try {
                    Looper.prepare();
                    downLoadApk();
                    searchStatus();
                    Looper.loop();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }.start();

    }

Android中的Looper類,是用來封裝消息循環和消息隊列的一個類,用于在android線程中進行消息處理。handler其實可以看做是一個工具類,用來向消息隊列中插入消息的。
先調用Looper.prepare()啟用Looper;Looper.loop(); loop函數從MessageQueue中從前往后取出Message,Looper.loop()中是個while循環,只有對它所在線程的Looper調用了quit()函數,Looper.loop()函數才能完成。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容