APP自動檢測版本及更新 - Android

我們偶爾會對自己的APP做更新,那么不免就需要把最新版本的app推送給用戶,所以今天動手實現(xiàn)一下app自動檢測版本及更新。實現(xiàn)思路大致是這樣的:
1、首先我們在服務器上建立一個version.txt文件,提供給客戶端最新版本的信息,內容如下:

//json數據格式
{"code":"2.0","update":"最新版本apk的地址"}

2、在啟動頁中獲取本機版本,并開啟線程獲取服務器的version.txt,并解析出最新版本號與本機對比。(通常在與服務器交互前,我會先ping一下服務器,來確保服務器以及網絡可用。)
3、如果版本號不同,那么就提示用戶版本需要升級。
4、當用戶同意升級,那么就下載最新版本APK,并自動安裝。

大致思路就是這樣,接著上代碼。

通過ping服務器,判斷服務器是否可用。

/**
     * 通過ping判斷是否可用
     * @return
     */
    public static boolean ping() {
        try {
            //服務器ip地址
            String ip = "***";
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " + ip);
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content;
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            int status = p.waitFor();
            if (status == 0) {
                return true;
            }
        }
        catch (IOException e) {}
        catch (InterruptedException e) {}
        return false;
    }

從服務器獲取APP最新版本信息。


/**
     * 獲取最新版本信息
     * @return
     * @throws IOException
     * @throws JSONException
     */
    private String getVersion() throws IOException, JSONException {
        URL url = new URL("http://***/version.txt");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setReadTimeout(8 * 1000);
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String string;
        string = bufferedReader.readLine();
        //對json數據進行解析
        JSONObject jsonObject = new JSONObject(string);
        String strings = jsonObject.getString("code");
        return strings;
    }

彈出對話框,用戶點擊確定開始下載最新版本APK,點擊取消不做任何動作。

/**
     * 彈出對話框
     */
    protected void showUpdataDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(this) ;
        builer.setTitle("版本升級");
        builer.setMessage("軟件更新");
        //當點確定按鈕時從服務器上下載 新的apk 然后安裝
        builer.setPositiveButton("確定", (dialog, which) -> downLoadApk());
        //當點取消按鈕時不做任何舉動
        builer.setNegativeButton("取消", (dialogInterface, i) -> {});
        AlertDialog dialog = builer.create();
        dialog.show();
    }

開始從服務器下載APK

    protected void downLoadApk() {
        //進度條
        final ProgressDialog pd;
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下載更新");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    File file = getFileFromServer("http://***/v.apk", pd);
                    //安裝APK
                    installApk(file);
                    pd.dismiss(); //結束掉進度條對話框
                } catch (Exception e) {
                }
            }}.start();
    }
public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{
        //如果相等的話表示當前的sdcard掛載在手機上并且是可用的
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //獲取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len ;
            int total=0;
            while((len =bis.read(buffer))!=-1){
                fos.write(buffer, 0, len);
                total+= len;
                //獲取當前下載量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        }
        else{
            return null;
        }
    }

最后通過Intent動作啟動安裝APK

protected void installApk(File file) {
        Intent intent = new Intent();
        //執(zhí)行動作
        intent.setAction(Intent.ACTION_VIEW);
        //執(zhí)行的數據類型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }
Screenshot_1489932904.png
Screenshot_1489932913.png

筆者能力有限,不足之處歡迎指出!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,812評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 《裕語言》速成開發(fā)手冊3.0 官方用戶交流:iApp開發(fā)交流(1) 239547050iApp開發(fā)交流(2) 10...
    葉染柒丶閱讀 28,715評論 5 20
  • 《ilua》速成開發(fā)手冊3.0 官方用戶交流:iApp開發(fā)交流(1) 239547050iApp開發(fā)交流(2) 1...
    葉染柒丶閱讀 11,462評論 0 11
  • 今天聽了這本書的前幾章,體會有幾點: 一是每個領導程級都有其需要的特殊能力,不能以上一個階段擅長的能力來應對本階段...
    Norman_Plus閱讀 272評論 0 1

友情鏈接更多精彩內容