Android不使用第三方升級庫實現應用升級

weixin_34116110發表於2017-03-07

現在很多第三方都提供應用升級的整合,可能只需要把jar包匯入,然後加入幾行程式碼就可以了,但是這樣的使用不利於我們對Android的理解。廢話不多說,先講講怎麼實現吧!

1、檢查版本號

獲取本地版本號:

public static String getVersionCode(Context context){
   PackageManager packageManager = context.getPackageManager();//獲取包管理器,用於後面獲取應用資訊
   try {
             PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);//獲取本應用資訊
         return packageInfo.versionCode+"";
                
      } catch (NameNotFoundException e) {
                // TODO Auto-generated catch block
         e.printStackTrace();
    }
    return "";
            
}

獲取網路上最新版本號:

//獲取最新版本資訊,判斷是否需要升級
public void getCloudVersion(){
   new Thread(){
                                @Override
      public void run() {
                    // TODO Auto-generated method stub
         try {
        URL url = new URL(GlobalURL.QUERYVERSION);//我的應用檢查版本的地址Url                             

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();//開啟一個網路連線
                           connection.setRequestMethod("POST");//設定請求method為post
                        DataOutputStream out = new DataOutputStream(connection.getOutputStream());//開啟一個輸出流
                        out.writeBytes("imei="+CommonUtil.getDeviceID(context)+"&soundNo=1");//需要提交給後臺伺服器的資料引數之間用&分割
                        InputStream inputStream = connection.getInputStream();//獲取輸入流,伺服器響應內容
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                         bufferedReader = new BufferedReader(inputStreamReader);
                        StringBuilder builder = new StringBuilder();//把輸入流包裝成字元緩衝輸入流,有人可能會問為什麼要用buffer,buffer是為了使兩個速度差異很大的端之間的交流不會因此而出現問題
                        String line;
                        while((line=bufferedReader.readLine()) != null){
                            builder.append(line);
                        }
                        JSONObject jsonObject = new JSONObject(builder.toString());
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        apkUrl = jsonObject1.getString("apkUrl");
                        version = jsonObject1.getString("version");
                        content = jsonObject1.getString("content");
                        if (Integer.parseInt(version)>Integer.parseInt(getVersionCode(context))) {
                            mHandler.sendEmptyMessage(SHOW_DOWNLOAD_DIALOG);//判斷到需要升級,則顯示升級提示框
                        }
//下面是一個檢查最新版本api返回的一個json例子                     //{"success":true,"code":"1","data":{"apkUrl":"http://192.168.63.4:8082/orange-web/res/apkfile/1463894203012422.apk","version":1,"content":"更新說明"}}
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    
                }}.start();
        }

2、詢問是否升級

private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case SHOW_DOWNLOAD_DIALOG:
                showDownloadDialog();
                break;

            default:
                break;
            }
        }
};

//顯示對話方塊,詢問是否更新
        public void showDownloadDialog(){
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("檢測到新版本   "+version);
            builder.setMessage(content);
            builder.setCancelable(false);
            builder.setPositiveButton("升級",new OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    initProgressDialog();
                    
                }
            });
            builder.setNegativeButton("暫不升級", new OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });
            builder.show();
        }
        

3、初始化關鍵控制元件開始下載更新

//初始化下載進度條
        public void initProgressDialog(){
            progressDialog = new ProgressDialog(context);
            progressDialog.setMessage("準備下載...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setOnCancelListener(new OnCancelListener() {
                
                @Override
                public void onCancel(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    httpHandler.cancel();
                }
            });
            progressDialog.show();
            downloadNewApk();
        }
        //下載更新apk
        public void downloadNewApk() {
            HttpUtils httpUtils = new HttpUtils();
            httpHandler = httpUtils.download(apkUrl, Environment.getExternalStorageDirectory()+"/Download/tingcheng.apk", new RequestCallBack() {
                @Override
                public void onLoading(long total, long current,
                        boolean isUploading) {
                    progressDialog.setMessage("正在下載...");
                    progressDialog.setProgress((int)current);
                    progressDialog.setMax((int)total);
                    progressDialog.setProgressNumberFormat(current/1024+"K"+"/"+total/1024+"K");
                }
                @Override
                public void onSuccess(ResponseInfo arg0) {
                    // TODO Auto-generated method stub
                    progressDialog.dismiss();
                    installAPK();
                }
                
                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    // TODO Auto-generated method stub
                    progressDialog.setMessage("下載失敗");
                    
                }
            });
        }

不需要使用第三方的升級庫,自己就可以做了 : )

相關文章