Android版本检测升级

来源:互联网 发布:网络分销平台排行 编辑:程序博客网 时间:2024/05/21 06:58

转载注明:Android开发中文站 » Android版本检测升级

我们应该都有类似的使用体验,当一款APP需要更新是,进入界面会提醒有新的更新是否更新,这里有那么几个步骤

1、首先检测当前版本

2、判断服务器中版本

3、如果有更新则点击更新,下载安装包,下载完成后自动安装

具体代码怎么实现呢?下面我们一起看一下

/*
 * 获取当前程序的版本号
 */
privateString getVersionName() throwsException{
    //获取packagemanager的实例
    PackageManager packageManager = getPackageManager();
    //getPackageName()是你当前类的包名,0代表是获取版本信息
    PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
    returnpackInfo.versionName;
}

读取服务器版本号

/*
 * 用pull解析器解析服务器返回的xml文件 (xml封装了版本号)
 */
publicstatic UpdataInfo getUpdataInfo(InputStream is) throwsException{
    XmlPullParser  parser = Xml.newPullParser();
    parser.setInput(is, "utf-8");//设置解析的数据源
    inttype = parser.getEventType();
    UpdataInfo info = newUpdataInfo();//实体
    while(type != XmlPullParser.END_DOCUMENT ){
        switch(type) {
        caseXmlPullParser.START_TAG:
            if("version".equals(parser.getName())){
                info.setVersion(parser.nextText()); //获取版本号
            }elseif ("url".equals(parser.getName())){
                info.setUrl(parser.nextText()); //获取要升级的APK文件
            }elseif ("description".equals(parser.getName())){
                info.setDescription(parser.nextText()); //获取该文件的信息
            }
            break;
        }
        type = parser.next();
    }
    returninfo;
}
下载

publicstatic File getFileFromServer(String path, ProgressDialog pd) throwsException{
    //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        URL url = newURL(path);
        HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        //获取到文件的大小
        pd.setMax(conn.getContentLength());
        InputStream is = conn.getInputStream();
        File file = newFile(Environment.getExternalStorageDirectory(), "updata.apk");
        FileOutputStream fos = newFileOutputStream(file);
        BufferedInputStream bis = newBufferedInputStream(is);
        byte[] buffer = newbyte[1024];
        intlen ;
        inttotal=0;
        while((len =bis.read(buffer))!=-1){
            fos.write(buffer, 0, len);
            total+= len;
            //获取当前下载量
            pd.setProgress(total);
        }
        fos.close();
        bis.close();
        is.close();
        returnfile;
    }
    else{
        returnnull;
    }
}
版本匹配、自动安装

/*
 * 从服务器获取xml解析并进行比对版本号
 */
publicclass CheckVersionTask implementsRunnable{
 
    publicvoid run() {
        try{
            //从资源文件获取服务器 地址
            String path = getResources().getString(R.string.serverurl);
            //包装成url的对象
            URL url = newURL(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 = newMessage();
                msg.what = UPDATA_CLIENT;
                handler.sendMessage(msg);
            }
        catch(Exception e) {
            // 待处理
            Message msg = newMessage();
            msg.what = GET_UNDATAINFO_ERROR;
            handler.sendMessage(msg);
            e.printStackTrace();
        }
    }
}
 
Handler handler = newHandler(){
 
    @Override
    publicvoid handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        switch(msg.what) {
        caseUPDATA_CLIENT:
            //对话框通知用户升级程序
            showUpdataDialog();
            break;
        caseGET_UNDATAINFO_ERROR:
            //服务器超时
            Toast.makeText(getApplicationContext(), "获取服务器更新信息失败"1).show();
            LoginMain();
            break;
        caseDOWN_ERROR:
            //下载apk失败
            Toast.makeText(getApplicationContext(), "下载新版本失败"1).show();
            LoginMain();
            break;
        }
    }
};
 
/*
 *
 * 弹出对话框通知用户更新程序
 *
 * 弹出对话框的步骤:
 *  1.创建alertDialog的builder.
 *  2.要给builder设置属性, 对话框的内容,样式,按钮
 *  3.通过builder 创建一个对话框
 *  4.对话框show()出来
 */
protectedvoid showUpdataDialog() {
    AlertDialog.Builder builer = newBuilder(this) ;
    builer.setTitle("版本升级");
    builer.setMessage(info.getDescription());
    //当点确定按钮时从服务器上下载 新的apk 然后安装
    builer.setPositiveButton("确定"newOnClickListener() {
    publicvoid onClick(DialogInterface dialog, intwhich) {
            Log.i(TAG,"下载apk,更新");
            downLoadApk();
        }
    });
    //当点取消按钮时进行登录
    builer.setNegativeButton("取消"newOnClickListener() {
        publicvoid onClick(DialogInterface dialog, intwhich) {
            // TODO Auto-generated method stub
            LoginMain();
        }
    });
    AlertDialog dialog = builer.create();
    dialog.show();
}
 
/*
 * 从服务器中下载APK
 */
protectedvoid downLoadApk() {
    finalProgressDialog pd;    //进度条对话框
    pd = new ProgressDialog(this);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setMessage("正在下载更新");
    pd.show();
    newThread(){
        @Override
        publicvoid run() {
            try{
                File file = DownLoadManager.getFileFromServer(info.getUrl(), pd);
                sleep(3000);
                installApk(file);
                pd.dismiss(); //结束掉进度条对话框
            catch(Exception e) {
                Message msg = newMessage();
                msg.what = DOWN_ERROR;
                handler.sendMessage(msg);
                e.printStackTrace();
            }
        }}.start();
}
 
//安装apk
protectedvoid installApk(File file) {
    Intent intent = newIntent();
    //执行动作
    intent.setAction(Intent.ACTION_VIEW);
    //执行的数据类型
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    startActivity(intent);
}
 
/*
 * 进入程序的主界面
 */
privatevoid LoginMain(){
    Intent intent = newIntent(this,MainActivity.class);
    startActivity(intent);
    //结束掉当前的activity
    this.finish();
}
相关类

publicclass UpdataInfo {
    privateString version;
    privateString url;
    privateString description;
    publicString getVersion() {
        returnversion;
    }
    publicvoid setVersion(String version) {
        this.version = version;
    }
    publicString getUrl() {
        returnurl;
    }
    publicvoid setUrl(String url) {
        this.url = url;
    }
    publicString getDescription() {
        returndescription;
    }
    publicvoid setDescription(String description) {
        this.description = description;
    }
}
相关布局

<?xmlversion="1.0"encoding="utf-8"?>
<info>
    <version&gt;2.0&lt;/version>
    <url>http://192.168.0.64:8080/mobilesafe.apk</url>
    <description>检测到最新版本,请及时更新!</description>
</info>

0 0
原创粉丝点击