Android自动检测版本及自动升级

http://blog.****.net/furongkang/article/details/6886526

步骤:

1.检测当前版本的信息AndroidManifest.xml-->manifest-->android:versionName。

2.从服务器获取版本号(版本号存在于xml文件中)并与当前检测到的版本进行匹配,如果不匹配,提示用户进行升级,如果匹配则进入程序主界面。

3.当提示用户进行版本升级时,如果用户点击了确定,系统将自动从服务器上下载并进行自动升级,如果点击取消将进入程序主界面。

效果图:

Android自动检测版本及自动升级Android自动检测版本及自动升级

Android自动检测版本及自动升级Android自动检测版本及自动升级

获取当前程序的版本号:

  1. /*
  2. *获取当前程序的版本号
  3. */
  4. privateStringgetVersionName()throwsException{
  5. //获取packagemanager的实例
  6. PackageManagerpackageManager=getPackageManager();
  7. //getPackageName()是你当前类的包名,0代表是获取版本信息
  8. PackageInfopackInfo=packageManager.getPackageInfo(getPackageName(),0);
  9. returnpackInfo.versionName;
  10. }
获取服务器端的版本号:

  1. /*
  2. *用pull解析器解析服务器返回的xml文件(xml封装了版本号)
  3. */
  4. publicstaticUpdataInfogetUpdataInfo(InputStreamis)throwsException{
  5. XmlPullParserparser=Xml.newPullParser();
  6. parser.setInput(is,"utf-8");//设置解析的数据源
  7. inttype=parser.getEventType();
  8. UpdataInfoinfo=newUpdataInfo();//实体
  9. while(type!=XmlPullParser.END_DOCUMENT){
  10. switch(type){
  11. caseXmlPullParser.START_TAG:
  12. if("version".equals(parser.getName())){
  13. info.setVersion(parser.nextText());//获取版本号
  14. }elseif("url".equals(parser.getName())){
  15. info.setUrl(parser.nextText());//获取要升级的APK文件
  16. }elseif("description".equals(parser.getName())){
  17. info.setDescription(parser.nextText());//获取该文件的信息
  18. }
  19. break;
  20. }
  21. type=parser.next();
  22. }
  23. returninfo;
  24. }
从服务器下载apk:

  1. publicstaticFilegetFileFromServer(Stringpath,ProgressDialogpd)throwsException{
  2. //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
  3. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
  4. URLurl=newURL(path);
  5. HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  6. conn.setConnectTimeout(5000);
  7. //获取到文件的大小
  8. pd.setMax(conn.getContentLength());
  9. InputStreamis=conn.getInputStream();
  10. Filefile=newFile(Environment.getExternalStorageDirectory(),"updata.apk");
  11. FileOutputStreamfos=newFileOutputStream(file);
  12. BufferedInputStreambis=newBufferedInputStream(is);
  13. byte[]buffer=newbyte[1024];
  14. intlen;
  15. inttotal=0;
  16. while((len=bis.read(buffer))!=-1){
  17. fos.write(buffer,0,len);
  18. total+=len;
  19. //获取当前下载量
  20. pd.setProgress(total);
  21. }
  22. fos.close();
  23. bis.close();
  24. is.close();
  25. returnfile;
  26. }
  27. else{
  28. returnnull;
  29. }
  30. }


匹配、下载、自动安装:

  1. /*
  2. *从服务器获取xml解析并进行比对版本号
  3. */
  4. publicclassCheckVersionTaskimplementsRunnable{
  5. publicvoidrun(){
  6. try{
  7. //从资源文件获取服务器地址
  8. Stringpath=getResources().getString(R.string.serverurl);
  9. //包装成url的对象
  10. URLurl=newURL(path);
  11. HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  12. conn.setConnectTimeout(5000);
  13. InputStreamis=conn.getInputStream();
  14. info=UpdataInfoParser.getUpdataInfo(is);
  15. if(info.getVersion().equals(versionname)){
  16. Log.i(TAG,"版本号相同无需升级");
  17. LoginMain();
  18. }else{
  19. Log.i(TAG,"版本号不同,提示用户升级");
  20. Messagemsg=newMessage();
  21. msg.what=UPDATA_CLIENT;
  22. handler.sendMessage(msg);
  23. }
  24. }catch(Exceptione){
  25. //待处理
  26. Messagemsg=newMessage();
  27. msg.what=GET_UNDATAINFO_ERROR;
  28. handler.sendMessage(msg);
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33. Handlerhandler=newHandler(){
  34. @Override
  35. publicvoidhandleMessage(Messagemsg){
  36. //TODOAuto-generatedmethodstub
  37. super.handleMessage(msg);
  38. switch(msg.what){
  39. caseUPDATA_CLIENT:
  40. //对话框通知用户升级程序
  41. showUpdataDialog();
  42. break;
  43. caseGET_UNDATAINFO_ERROR:
  44. //服务器超时
  45. Toast.makeText(getApplicationContext(),"获取服务器更新信息失败",1).show();
  46. LoginMain();
  47. break;
  48. caseDOWN_ERROR:
  49. //下载apk失败
  50. Toast.makeText(getApplicationContext(),"下载新版本失败",1).show();
  51. LoginMain();
  52. break;
  53. }
  54. }
  55. };
  56. /*
  57. *
  58. *弹出对话框通知用户更新程序
  59. *
  60. *弹出对话框的步骤:
  61. *1.创建alertDialog的builder.
  62. *2.要给builder设置属性,对话框的内容,样式,按钮
  63. *3.通过builder创建一个对话框
  64. *4.对话框show()出来
  65. */
  66. protectedvoidshowUpdataDialog(){
  67. AlertDialog.Builderbuiler=newBuilder(this);
  68. builer.setTitle("版本升级");
  69. builer.setMessage(info.getDescription());
  70. //当点确定按钮时从服务器上下载新的apk然后安装
  71. builer.setPositiveButton("确定",newOnClickListener(){
  72. publicvoidonClick(DialogInterfacedialog,intwhich){
  73. Log.i(TAG,"下载apk,更新");
  74. downLoadApk();
  75. }
  76. });
  77. //当点取消按钮时进行登录
  78. builer.setNegativeButton("取消",newOnClickListener(){
  79. publicvoidonClick(DialogInterfacedialog,intwhich){
  80. //TODOAuto-generatedmethodstub
  81. LoginMain();
  82. }
  83. });
  84. AlertDialogdialog=builer.create();
  85. dialog.show();
  86. }
  87. /*
  88. *从服务器中下载APK
  89. */
  90. protectedvoiddownLoadApk(){
  91. finalProgressDialogpd;//进度条对话框
  92. pd=newProgressDialog(this);
  93. pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  94. pd.setMessage("正在下载更新");
  95. pd.show();
  96. newThread(){
  97. @Override
  98. publicvoidrun(){
  99. try{
  100. Filefile=DownLoadManager.getFileFromServer(info.getUrl(),pd);
  101. sleep(3000);
  102. installApk(file);
  103. pd.dismiss();//结束掉进度条对话框
  104. }catch(Exceptione){
  105. Messagemsg=newMessage();
  106. msg.what=DOWN_ERROR;
  107. handler.sendMessage(msg);
  108. e.printStackTrace();
  109. }
  110. }}.start();
  111. }
  112. //安装apk
  113. protectedvoidinstallApk(Filefile){
  114. Intentintent=newIntent();
  115. //执行动作
  116. intent.setAction(Intent.ACTION_VIEW);
  117. //执行的数据类型
  118. intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
  119. startActivity(intent);
  120. }
  121. /*
  122. *进入程序的主界面
  123. */
  124. privatevoidLoginMain(){
  125. Intentintent=newIntent(this,MainActivity.class);
  126. startActivity(intent);
  127. //结束掉当前的activity
  128. this.finish();
  129. }


UpdataInfo:

  1. publicclassUpdataInfo{
  2. privateStringversion;
  3. privateStringurl;
  4. privateStringdescription;
  5. publicStringgetVersion(){
  6. returnversion;
  7. }
  8. publicvoidsetVersion(Stringversion){
  9. this.version=version;
  10. }
  11. publicStringgetUrl(){
  12. returnurl;
  13. }
  14. publicvoidsetUrl(Stringurl){
  15. this.url=url;
  16. }
  17. publicStringgetDescription(){
  18. returndescription;
  19. }
  20. publicvoidsetDescription(Stringdescription){
  21. this.description=description;
  22. }
  23. }


update.xml:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <info>
  3. <version>2.0</version>
  4. <url>http://192.168.1.187:8080/mobilesafe.apk</url>
  5. <description>检测到最新版本,请及时更新!</description>
  6. </info>