Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android App 版本更新提示的完整流程

編輯:關於 Android 程式設計

幾乎每個 Android App 都會有版本更新的功能。本文示範一套完整的更新流程,主要用到 AsyncTask 非同步載入、HTTP 協議、JSON 解析與版本號取得等技術。整體步驟是:點擊檢查 → 向伺服器查詢最新版本 → 比對版本號 → 若有新版則下載並安裝,否則提示已是最新。

activity_main.xml

介面只需一個用來觸發檢查的按鈕:

MainActivity.java

點擊按鈕後啟動 AsyncTask,在背景執行緒向伺服器查詢最新版本號;若新版本號大於當前版本,則執行下載,否則提示已是最新:

public class MainActivity extends Activity {
    Button m_btnCheckNewestVersion;
    long m_newVerCode;      // 最新版的版本號
    String m_newVerName;    // 最新版的版本名
    String m_appNameStr;    // 下載到本地的檔名
    Handler m_mainHandler;
    ProgressDialog m_progressDlg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initVariable();
        m_btnCheckNewestVersion.setOnClickListener(btnClickListener);
    }
    private void initVariable() {
        m_btnCheckNewestVersion = (Button) findViewById(R.id.chek_newest_version);
        m_mainHandler = new Handler();
        m_progressDlg = new ProgressDialog(this);
        m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        m_progressDlg.setIndeterminate(false);
        m_appNameStr = "haha.apk";
    }
    OnClickListener btnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new checkNewestVersionAsyncTask().execute();
        }
    };
    class checkNewestVersionAsyncTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            if (postCheckNewestVersionCommand2Server()) {
                int vercode = Common.getVerCode(getApplicationContext());
                return m_newVerCode > vercode;
            }
            return false;
        }
        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                doNewVersionUpdate();
            } else {
                notNewVersionDlgShow();
            }
            super.onPostExecute(result);
        }
    }
    /** 從伺服器取得最新版本號,成功回傳 true */
    private Boolean postCheckNewestVersionCommand2Server() {
        StringBuilder builder = new StringBuilder();
        try {
            List<NameValuePair> vps = new ArrayList<NameValuePair>();
            vps.add(new BasicNameValuePair("action", "checkNewestVersion"));
            builder = Common.post_to_server(vps);
            JSONArray jsonArray = new JSONArray(builder.toString());
            if (jsonArray.length() > 0) {
                if (jsonArray.getJSONObject(0).getInt("id") == 1) {
                    m_newVerName = jsonArray.getJSONObject(0).getString("verName");
                    m_newVerCode = jsonArray.getJSONObject(0).getLong("verCode");
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            m_newVerName = "";
            m_newVerCode = -1;
            return false;
        }
    }
    /** 提示更新新版本 */
    private void doNewVersionUpdate() {
        int verCode = Common.getVerCode(getApplicationContext());
        String verName = Common.getVerName(getApplicationContext());
        String str = "當前版本:" + verName + " Code:" + verCode + " ,發現新版本:" + m_newVerName + " Code:" + m_newVerCode + " ,是否更新?";
        Dialog dialog = new AlertDialog.Builder(this).setTitle("軟件更新").setMessage(str)
            .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    m_progressDlg.setTitle("正在下載");
                    m_progressDlg.setMessage("請稍候...");
                    downFile(Common.UPDATESOFTADDRESS);
                }
            })
            .setNegativeButton("暫不更新", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    finish();
                }
            }).create();
        dialog.show();
    }
    /** 提示當前為最新版本 */
    private void notNewVersionDlgShow() {
        int verCode = Common.getVerCode(this);
        String verName = Common.getVerName(this);
        String str = "當前版本:" + verName + " Code:" + verCode + ",已是最新版,無需更新!";
        Dialog dialog = new AlertDialog.Builder(this).setTitle("軟件更新").setMessage(str)
            .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) { finish(); }
            }).create();
        dialog.show();
    }
    private void downFile(final String url) {
        m_progressDlg.show();
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                try {
                    HttpResponse response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();
                    m_progressDlg.setMax((int) length);
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(Environment.getExternalStorageDirectory(), m_appNameStr);
                        fileOutputStream = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            if (length > 0) m_progressDlg.setProgress(count);
                        }
                    }
                    if (fileOutputStream != null) fileOutputStream.close();
                    down();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    /** 下載完成,通知更新 UI 並安裝 */
    private void down() {
        m_mainHandler.post(new Runnable() {
            public void run() {
                m_progressDlg.cancel();
                update();
            }
        });
    }
    /** 安裝程式 */
    void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), m_appNameStr)),
            "application/vnd.android.package-archive");
        startActivity(intent);
    }
}

Common.java

類似一個工具類,封裝了向伺服器 POST 請求、取得版本號與版本名等方法。下載完成後即呼叫安裝:

public class Common {
    public static final String SERVER_IP = "https://192.168.1.105/";
    public static final String SERVER_ADDRESS = SERVER_IP + "try_downloadFile_progress_server/index.php";
    public static final String UPDATESOFTADDRESS = SERVER_IP + "try_downloadFile_progress_server/update_pakage/baidu.apk";
    /** 向伺服器發送查詢請求,回傳 StringBuilder */
    public static StringBuilder post_to_server(List<NameValuePair> vps) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpost = new HttpPost(SERVER_ADDRESS);
            StringBuilder builder = new StringBuilder();
            httpost.setEntity(new UrlEncodedFormEntity(vps, HTTP.UTF_8));
            HttpResponse response = httpclient.execute(httpost);
            if (response.getEntity() != null) {
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));
                String s = reader.readLine();
                for (; s != null; s = reader.readLine()) {
                    builder.append(s);
                }
            }
            return builder;
        } catch (Exception e) {
            return null;
        } finally {
            try { httpclient.getConnectionManager().shutdown(); } catch (Exception e) { }
        }
    }
    /** 取得軟件版本號 */
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo(
                "com.example.try_downloadfile_progress", 0).versionCode;
        } catch (NameNotFoundException e) { }
        return verCode;
    }
    /** 取得版本名稱 */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(
                "com.example.try_downloadfile_progress", 0).versionName;
        } catch (NameNotFoundException e) { }
        return verName;
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved