Android自动检测版本及自动升级
http://blog.****.net/furongkang/article/details/6886526
步骤:
1.检测当前版本的信息AndroidManifest.xml-->manifest-->android:versionName。
2.从服务器获取版本号(版本号存在于xml文件中)并与当前检测到的版本进行匹配,如果不匹配,提示用户进行升级,如果匹配则进入程序主界面。
3.当提示用户进行版本升级时,如果用户点击了确定,系统将自动从服务器上下载并进行自动升级,如果点击取消将进入程序主界面。
效果图:
获取当前程序的版本号:
- /*
- *获取当前程序的版本号
- */
- privateStringgetVersionName()throwsException{
- //获取packagemanager的实例
- PackageManagerpackageManager=getPackageManager();
- //getPackageName()是你当前类的包名,0代表是获取版本信息
- PackageInfopackInfo=packageManager.getPackageInfo(getPackageName(),0);
- returnpackInfo.versionName;
- }
- /*
- *用pull解析器解析服务器返回的xml文件(xml封装了版本号)
- */
- publicstaticUpdataInfogetUpdataInfo(InputStreamis)throwsException{
- XmlPullParserparser=Xml.newPullParser();
- parser.setInput(is,"utf-8");//设置解析的数据源
- inttype=parser.getEventType();
- UpdataInfoinfo=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;
- }
- publicstaticFilegetFileFromServer(Stringpath,ProgressDialogpd)throwsException{
- //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
- if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- URLurl=newURL(path);
- HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
- conn.setConnectTimeout(5000);
- //获取到文件的大小
- pd.setMax(conn.getContentLength());
- InputStreamis=conn.getInputStream();
- Filefile=newFile(Environment.getExternalStorageDirectory(),"updata.apk");
- FileOutputStreamfos=newFileOutputStream(file);
- BufferedInputStreambis=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解析并进行比对版本号
- */
- publicclassCheckVersionTaskimplementsRunnable{
- publicvoidrun(){
- try{
- //从资源文件获取服务器地址
- Stringpath=getResources().getString(R.string.serverurl);
- //包装成url的对象
- URLurl=newURL(path);
- HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
- conn.setConnectTimeout(5000);
- InputStreamis=conn.getInputStream();
- info=UpdataInfoParser.getUpdataInfo(is);
- if(info.getVersion().equals(versionname)){
- Log.i(TAG,"版本号相同无需升级");
- LoginMain();
- }else{
- Log.i(TAG,"版本号不同,提示用户升级");
- Messagemsg=newMessage();
- msg.what=UPDATA_CLIENT;
- handler.sendMessage(msg);
- }
- }catch(Exceptione){
- //待处理
- Messagemsg=newMessage();
- msg.what=GET_UNDATAINFO_ERROR;
- handler.sendMessage(msg);
- e.printStackTrace();
- }
- }
- }
- Handlerhandler=newHandler(){
- @Override
- publicvoidhandleMessage(Messagemsg){
- //TODOAuto-generatedmethodstub
- 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()出来
- */
- protectedvoidshowUpdataDialog(){
- AlertDialog.Builderbuiler=newBuilder(this);
- builer.setTitle("版本升级");
- builer.setMessage(info.getDescription());
- //当点确定按钮时从服务器上下载新的apk然后安装
- builer.setPositiveButton("确定",newOnClickListener(){
- publicvoidonClick(DialogInterfacedialog,intwhich){
- Log.i(TAG,"下载apk,更新");
- downLoadApk();
- }
- });
- //当点取消按钮时进行登录
- builer.setNegativeButton("取消",newOnClickListener(){
- publicvoidonClick(DialogInterfacedialog,intwhich){
- //TODOAuto-generatedmethodstub
- LoginMain();
- }
- });
- AlertDialogdialog=builer.create();
- dialog.show();
- }
- /*
- *从服务器中下载APK
- */
- protectedvoiddownLoadApk(){
- finalProgressDialogpd;//进度条对话框
- pd=newProgressDialog(this);
- pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- pd.setMessage("正在下载更新");
- pd.show();
- newThread(){
- @Override
- publicvoidrun(){
- try{
- Filefile=DownLoadManager.getFileFromServer(info.getUrl(),pd);
- sleep(3000);
- installApk(file);
- pd.dismiss();//结束掉进度条对话框
- }catch(Exceptione){
- Messagemsg=newMessage();
- msg.what=DOWN_ERROR;
- handler.sendMessage(msg);
- e.printStackTrace();
- }
- }}.start();
- }
- //安装apk
- protectedvoidinstallApk(Filefile){
- Intentintent=newIntent();
- //执行动作
- intent.setAction(Intent.ACTION_VIEW);
- //执行的数据类型
- intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
- startActivity(intent);
- }
- /*
- *进入程序的主界面
- */
- privatevoidLoginMain(){
- Intentintent=newIntent(this,MainActivity.class);
- startActivity(intent);
- //结束掉当前的activity
- this.finish();
- }
UpdataInfo:
- publicclassUpdataInfo{
- privateStringversion;
- privateStringurl;
- privateStringdescription;
- publicStringgetVersion(){
- returnversion;
- }
- publicvoidsetVersion(Stringversion){
- this.version=version;
- }
- publicStringgetUrl(){
- returnurl;
- }
- publicvoidsetUrl(Stringurl){
- this.url=url;
- }
- publicStringgetDescription(){
- returndescription;
- }
- publicvoidsetDescription(Stringdescription){
- this.description=description;
- }
- }
update.xml:
- <?xmlversion="1.0"encoding="utf-8"?>
- <info>
- <version>2.0</version>
- <url>http://192.168.1.187:8080/mobilesafe.apk</url>
- <description>检测到最新版本,请及时更新!</description>
- </info>