Android版本檢測升級

來源:互聯網
上載者:User

標籤:android   版本檢測   升級   

我們應該都有類似的使用體驗,當一款APP需要更新是,進入介面會提醒有新的更新是否更新,這裡有那麼幾個步驟

1首先檢測目前的版本
2判斷伺服器中版本
3如果有更新則點擊更新,下載安裝包,下載完成後自動安裝

具體代碼怎麼實現呢?下面我們一起看一下

    /*     * 擷取當前程式的版本號碼      */    private String getVersionName() throws Exception{        //擷取packagemanager的執行個體         PackageManager packageManager = getPackageManager();        //getPackageName()是你當前類的包名,0代表是擷取版本資訊        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);        return packInfo.versionName;     }

讀取伺服器版本號碼

    /*     * 用pull解析器解析伺服器返回的xml檔案 (xml封裝了版本號碼)     */    public static UpdataInfo getUpdataInfo(InputStream is) throws Exception{        XmlPullParser  parser = Xml.newPullParser();          parser.setInput(is, "utf-8");//設定解析的資料來源         int type = parser.getEventType();        UpdataInfo info = new UpdataInfo();//實體        while(type != XmlPullParser.END_DOCUMENT ){            switch (type) {            case XmlPullParser.START_TAG:                if("version".equals(parser.getName())){                    info.setVersion(parser.nextText()); //擷取版本號碼                }else if ("url".equals(parser.getName())){                    info.setUrl(parser.nextText()); //擷取要升級的APK檔案                }else if ("description".equals(parser.getName())){                    info.setDescription(parser.nextText()); //擷取該檔案的資訊                }                break;            }            type = parser.next();        }        return info;    }

下載

    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;        }    }

版本匹配、自動安裝

    /*     * 從伺服器擷取xml解析並進行比對版本號碼      */    public class CheckVersionTask implements Runnable{        public void run() {            try {                //從資源檔擷取伺服器 地址                 String path = getResources().getString(R.string.serverurl);                //封裝成url的對象                 URL url = new URL(path);                HttpURLConnection conn =  (HttpURLConnection) url.openConnection();                 conn.setConnectTimeout(5000);                InputStream is =conn.getInputStream();                 info =  UpdataInfoParser.getUpdataInfo(is);                if(info.getVersion().equals(versionname)){                    Log.i(TAG,"版本號碼相同無需升級");                    LoginMain();                }else{                    Log.i(TAG,"版本號碼不同 ,提示使用者升級 ");                    Message msg = new Message();                    msg.what = UPDATA_CLIENT;                    handler.sendMessage(msg);                }            } catch (Exception e) {                // 待處理                 Message msg = new Message();                msg.what = GET_UNDATAINFO_ERROR;                handler.sendMessage(msg);                e.printStackTrace();            }         }    }    Handler handler = new Handler(){        @Override        public void handleMessage(Message msg) {            // TODO Auto-generated method stub            super.handleMessage(msg);            switch (msg.what) {            case UPDATA_CLIENT:                //對話方塊通知使用者升級程式                 showUpdataDialog();                break;            case GET_UNDATAINFO_ERROR:                //伺服器逾時                 Toast.makeText(getApplicationContext(), "擷取伺服器更新資訊失敗", 1).show();                LoginMain();                break;              case DOWN_ERROR:                //下載apk失敗                Toast.makeText(getApplicationContext(), "下載新版本失敗", 1).show();                LoginMain();                break;              }        }    };    /*     *      * 彈出對話方塊通知使用者更新程式      *      * 彈出對話方塊的步驟:     *  1.建立alertDialog的builder.       *  2.要給builder設定屬性, 對話方塊的內容,樣式,按鈕     *  3.通過builder 建立一個對話方塊     *  4.對話方塊show()出來       */    protected void showUpdataDialog() {        AlertDialog.Builder builer = new Builder(this) ;         builer.setTitle("版本升級");        builer.setMessage(info.getDescription());        //當點確定按鈕時從伺服器上下載 新的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) {                // TODO Auto-generated method stub                LoginMain();            }        });        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 = DownLoadManager.getFileFromServer(info.getUrl(), pd);                    sleep(3000);                    installApk(file);                    pd.dismiss(); //結束掉進度條對話方塊                } catch (Exception e) {                    Message msg = new Message();                    msg.what = DOWN_ERROR;                    handler.sendMessage(msg);                    e.printStackTrace();                }            }}.start();    }    //安裝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);    }    /*     * 進入程式的主介面     */    private void LoginMain(){        Intent intent = new Intent(this,MainActivity.class);        startActivity(intent);        //結束掉當前的activity         this.finish();    }

相關類

public class UpdataInfo {    private String version;    private String url;    private String description;    public String getVersion() {        return version;    }    public void setVersion(String version) {        this.version = version;    }    public String getUrl() {        return url;    }    public void setUrl(String url) {        this.url = url;    }    public String getDescription() {        return description;    }    public void setDescription(String description) {        this.description = description;    }}

相關布局

<?xml version="1.0" encoding="utf-8"?><info>    <version>2.0</version>    <url>http://192.168.0.64:8080/mobilesafe.apk</url>    <description>檢測到最新版本,請及時更新!</description></info>

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Android版本檢測升級

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.