2019年3月29日 星期五

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

目前遇到 Android App 未佈到 Google Play,但可以由私有伺器服取得更新版,進而更新,參考到一些做法,記錄一下
1.首先在伺服器上建立一個version.json文件,提供給客戶端最新版本的信息,內容如下:

//json資料格式
{"code":"2.0","update":"最新版本apk的地址"}
2.在啟始頁中取得本機版本,並開啟連線取得伺服器的version.json,並解析出最新版本號與本機對比。(通常在與伺服器連線前,先Ping一下伺服器,來確保伺服器以及網路可用。)

3. 如果版本號不同,那就提示用戶版本需要升級。
4.當用戶同意升級,那麼就下載最新版本APK,並自動安裝。

大致流程就是這樣,接著上Code 。

通過 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();
        //執行動作
        intent.setAction(Intent.ACTION_VIEW);
        //報行的資料類型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }
以上完畢。 參考網址: https://www.jianshu.com/p/2818d062a8f0

沒有留言:

張貼留言