實現版本更新


下面會通過代碼和解說的方式簡單去實現

  • 首先上方用到一個handler 去實現吐絲
Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case 0:
                Toast.makeText(MainActivity.this, "版本號相同無需升級!", 0).show();
                break;
            case 1:
                // 升級的彈框
                showUpdataDialog();
                Toast.makeText(MainActivity.this, "版本號不同需要升級!", 0).show();
                break;
            case 2:

                break;

            default:
                break;
            }

        };
    };

- 在onCreate方法中的調用

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        TextView tvname = (TextView) findViewById(R.id.tv_main_pagename);
       //檢測是否獲取到當前的版本號
        String versionName = getVersionName();
        tvname.setText("當前版本號:" + versionName);
    }


 - 獲取本機的版本信息
    private String getVersionName() {
        // getPackageName()是你當前類的包名,0代表是獲取版本信息
        PackageInfo packInfo = null;
        try {
            // 獲取packagemanager的實例
            PackageManager packageManager = this.getPackageManager();
            packInfo = packageManager.getPackageInfo(this.getPackageName(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return packInfo.versionName;
    }
  • 通過通過一個按鈕的點擊事件去實現版本更新的操作
// 版本更行的點擊事件
    public void versions(View v) {
        // 版本更新的操作,  這個方法在下方實現
        checkVersionTesk();
    }
  • 從服務器獲得 版本號 並且跟 當前的進行對比
public void checkVersionTesk() {

        new Thread() {
            private BanBean getname;

            @Override
            public void run() {
                // TODO Auto-generated method stub
                // 版本更新的接口   這只是我的
                String path = "http://www.oschina.net/MobileAppVersion.xml";
                try {
                //網絡請求
                    URL url = new URL(path);
                    HttpURLConnection openConnection = (HttpURLConnection) url
                            .openConnection();
                    int responseCode = openConnection.getResponseCode();
                    if (responseCode == 200) {
                        InputStream inputStream = openConnection
                                .getInputStream();
                        getname = getname(inputStream);
                        // 返回對象 得到的信息
                        String versionCode = getname.getVersionCode();
                        downloadUrl = getname.getDownloadUrl();
                        if (versionCode.equals(versionName)) {
                            // 不需要升級
                            handler.sendEmptyMessage(0);
                        } else {
                            // 需要升級
                            handler.sendEmptyMessage(1);
                        }

                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }
  • 彈出對話框通知用戶更新程序
    彈出對話框的步驟: 1.創建alertDialog的builder. 2.要給builder設置屬性, 對話框的內容,樣式,按鈕
    3.通過builder 創建一個對話框 4.對話框show()出來
//此方法在handler中調用了
public void showUpdataDialog() {

        AlertDialog.Builder builer = new Builder(MainActivity.this);
        builer.setTitle("版本升級");
        builer.setMessage("檢測到最新版本,確定要升級嗎?");
        // 當點確定按鈕時從服務器上下載 新的apk 然後安裝
        builer.setPositiveButton("確定", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Log.i(TAG, "下載apk,更新");
                 downLoadApk();
            }
        });
        // 當點取消按鈕時進行登錄
        builer.setNegativeButton("取消", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }

 - 從服務器中下載APK
 - 
 // 安裝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");// 編者按:此處Android應爲android,否則造成安裝不了
startActivity(intent);
}
  • 從服務器下載apk:
public static File getFileFromServer(String path, ProgressDialog pd) {
            // 如果相等的話表示當前的sdcard掛載在手機上並且是可用的
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                try {

                    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;
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                return null;
            }
            return null;
        }
  • // 通過xml 解析版本更新的信息
public BanBean getname(InputStream inputStream) {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "utf-8");
            int eventType = parser.getEventType();
            BanBean banBean = new BanBean();
            while (eventType != parser.END_DOCUMENT) {
                String name = parser.getName();
                switch (eventType) {
                case XmlPullParser.START_TAG:
                    if ("versionCode".equals(name)) {
                        banBean.setVersionCode(parser.nextText());
                    } else if ("versionName".equals(name)) {
                        banBean.setVersionName(parser.nextText());
                    } else if ("downloadUrl".equals(name)) {
                        banBean.setDownloadUrl(parser.nextText());
                    }
                    break;

                default:
                    break;
                }
                eventType = parser.next();
            }
            return banBean;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章