一、首先,参考了以下文章《Android自动检测版本及自动升级

http://www.linuxidc.com/Linux/2011-10/45718p2.htm:

步骤:

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

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

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

[java] view plain copy
  1. 获取当前程序的版本号:
  2. 1./*
  3. 2.*获取当前程序的版本号
  4. 3.*/
  5. 4.privateStringgetVersionName()throwsException{
  6. 5.//获取packagemanager的实例
  7. 6.PackageManagerpackageManager=getPackageManager();
  8. 7.//getPackageName()是你当前类的包名,0代表是获取版本信息
  9. 8.PackageInfopackInfo=packageManager.getPackageInfo(getPackageName(),0);
  10. 9.returnpackInfo.versionName;
  11. 10.}
[java] view plain copy
  1. 获取服务器端的版本号:
  2. 1./*
  3. 2.*用pull解析器解析服务器返回的xml文件(xml封装了版本号)
  4. 3.*/
  5. 4.publicstaticUpdataInfogetUpdataInfo(InputStreamis)throwsException{
  6. 5.XmlPullParserparser=Xml.newPullParser();
  7. 6.parser.setInput(is,"utf-8");//设置解析的数据源
  8. 7.inttype=parser.getEventType();
  9. 8.UpdataInfoinfo=newUpdataInfo();//实体
  10. 9.while(type!=XmlPullParser.END_DOCUMENT){
  11. 10.switch(type){
  12. 11.caseXmlPullParser.START_TAG:
  13. 12.if("version".equals(parser.getName())){
  14. 13.info.setVersion(parser.nextText());//获取版本号
  15. 14.}elseif("url".equals(parser.getName())){
  16. 15.info.setUrl(parser.nextText());//获取要升级的APK文件
  17. 16.}elseif("description".equals(parser.getName())){
  18. 17.info.setDescription(parser.nextText());//获取该文件的信息
  19. 18.}
  20. 19.break;
  21. 20.}
  22. 21.type=parser.next();
  23. 22.}
  24. 23.returninfo;
  25. 24.}
[java] view plain copy
  1. 从服务器下载apk:
  2. 1.publicstaticFilegetFileFromServer(Stringpath,ProgressDialogpd)throwsException{
  3. 2.//如果相等的话表示当前的sdcard挂载在手机上并且是可用的
  4. 3.if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
  5. 4.URLurl=newURL(path);
  6. 5.HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  7. 6.conn.setConnectTimeout(5000);
  8. 7.//获取到文件的大小
  9. 8.pd.setMax(conn.getContentLength());
  10. 9.InputStreamis=conn.getInputStream();
  11. 10.Filefile=newFile(Environment.getExternalStorageDirectory(),"updata.apk");
  12. 11.FileOutputStreamfos=newFileOutputStream(file);
  13. 12.BufferedInputStreambis=newBufferedInputStream(is);
  14. 13.byte[]buffer=newbyte[1024];
  15. 14.intlen;
  16. 15.inttotal=0;
  17. 16.while((len=bis.read(buffer))!=-1){
  18. 17.fos.write(buffer,0,len);
  19. 18.total+=len;
  20. 19.//获取当前下载量
  21. 20.pd.setProgress(total);
  22. 21.}
  23. 22.fos.close();
  24. 23.bis.close();
  25. 24.is.close();
  26. 25.returnfile;
  27. 26.}
  28. 27.else{
  29. 28.returnnull;
  30. 29.}
  31. 30.}

匹配、下载、自动安装:

[java] view plain copy
  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. }
[java] view plain copy
  1. Handlerhandler=newHandler(){
  2. @Override
  3. publicvoidhandleMessage(Messagemsg){
  4. //TODOAuto-generatedmethodstub
  5. super.handleMessage(msg);
  6. switch(msg.what){
  7. caseUPDATA_CLIENT:
  8. //对话框通知用户升级程序
  9. showUpdataDialog();
  10. break;
  11. caseGET_UNDATAINFO_ERROR:
  12. //服务器超时
  13. Toast.makeText(getApplicationContext(),"获取服务器更新信息失败",1).show();
  14. LoginMain();
  15. break;
  16. caseDOWN_ERROR:
  17. //下载apk失败
  18. Toast.makeText(getApplicationContext(),"下载新版本失败",1).show();
  19. LoginMain();
  20. break;
  21. }
  22. }
  23. };
[java] view plain copy
  1. /*
  2. *
  3. *弹出对话框通知用户更新程序
  4. *
  5. *弹出对话框的步骤:
  6. *1.创建alertDialog的builder.
  7. *2.要给builder设置属性,对话框的内容,样式,按钮
  8. *3.通过builder创建一个对话框
  9. *4.对话框show()出来
  10. */
  11. protectedvoidshowUpdataDialog(){
  12. AlertDialog.Builderbuiler=newBuilder(this);
  13. builer.setTitle("版本升级");
  14. builer.setMessage(info.getDescription());
  15. //当点确定按钮时从服务器上下载新的apk然后安装
  16. builer.setPositiveButton("确定",newOnClickListener(){
  17. publicvoidonClick(DialogInterfacedialog,intwhich){
  18. Log.i(TAG,"下载apk,更新");
  19. downLoadApk();
  20. }
  21. });
  22. //当点取消按钮时进行登录
  23. builer.setNegativeButton("取消",newOnClickListener(){
  24. publicvoidonClick(DialogInterfacedialog,intwhich){
  25. //TODOAuto-generatedmethodstub
  26. LoginMain();
  27. }
  28. });
  29. AlertDialogdialog=builer.create();
  30. dialog.show();
  31. }
[java] view plain copy
  1. /*
  2. *从服务器中下载APK
  3. */
  4. protectedvoiddownLoadApk(){
  5. finalProgressDialogpd;//进度条对话框
  6. pd=newProgressDialog(this);
  7. pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  8. pd.setMessage("正在下载更新");
  9. pd.show();
  10. newThread(){
  11. @Override
  12. publicvoidrun(){
  13. try{
  14. Filefile=DownLoadManager.getFileFromServer(info.getUrl(),pd);
  15. sleep(3000);
  16. installApk(file);
  17. pd.dismiss();//结束掉进度条对话框
  18. }catch(Exceptione){
  19. Messagemsg=newMessage();
  20. msg.what=DOWN_ERROR;
  21. handler.sendMessage(msg);
  22. e.printStackTrace();
  23. }
  24. }}.start();
  25. }
[java] view plain copy
  1. //安装apk
  2. protectedvoidinstallApk(Filefile){
  3. Intentintent=newIntent();
  4. //执行动作
  5. intent.setAction(Intent.ACTION_VIEW);
  6. //执行的数据类型
  7. intent.setDataAndType(Uri.fromFile(file),"application/vnd.Android.package-archive");//编者按:此处Android应为android,否则造成安装不了
  8. startActivity(intent);
  9. }
[java] view plain copy
  1. /*
  2. *进入程序的主界面
  3. */
  4. privatevoidLoginMain(){
  5. Intentintent=newIntent(this,MainActivity.class);
  6. startActivity(intent);
  7. //结束掉当前的activity
  8. this.finish();
  9. }

二、参考后使用情况:
1.可以下载apk,但安装失败:

1)以为配置文件中需定义了android.permission.INSTALL_PACKAGES,其实不需;

2)以为是要在执行安装的activity中配置

[html] view plain copy
  1. <intent-filter>
  2. <actionandroid:name="android.intent.action.VIEW"/>
  3. <categoryandroid:name="android.intent.category.DEFAULT"/>
  4. </intent-filter>

,其实不是;

3)代码中application/vnd.Android.package-archive有一个字母A大写了,改小写后解决;

更多相关文章

  1. 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
  2. Android屏幕分辨率正确获取及PX,DPI,DP,SP等的对应关系
  3. android“设置”里的版本号
  4. android 获取唯一标识
  5. android拍照与读取相册
  6. Android(安卓)热点开关状态的判断和获取热点ssid
  7. Andorid Dialog 示例【慢慢更新】
  8. Android软键盘适配问题
  9. AIR Native Extension的使用(Android)一 : 打包ane

随机推荐

  1. 详细Android Studio + NDK范例
  2. 如何扩大一个view的touch和click响应区域
  3. HttpURLConnection(java.net.CookieManage
  4. Android如何判断手机卡是SIM卡或者USIM卡
  5. 简单介绍Android应用特色及详解四大组件
  6. 什么在Android M中被弃用?
  7. Android 3.2 以上转屏,切换屏幕,横竖屏(onC
  8. Android-SurfaceView拍照录像
  9. ListView的上拉弹簧、下拉弹簧,下拉弹簧时
  10. arcgis for android 开发的导航的部分 请