转发网址:http://www.open-open.com/lib/view/open1339581191209.html


步骤:

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

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

其中xml文件的内容有:(里面主要有3个元素,版本号、url地址、相关信息)

1 2 3 4 5 <upgrade> <version> 2 </version> <url>http: //10.0.2.2:8080/myapp/Test.apk</url> 版本更新至 2.0 ,谢谢!</about> </upgrade>

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

?
1 2 3 4 5 6 7 8 9 10 11 12 获取当前程序的版本号: 1./* 2. * 获取当前程序的版本号 3. */ 4.privateString getVersionName() throwsException{ 5.//获取packagemanager的实例 6. PackageManager packageManager = getPackageManager(); 7.//getPackageName()是你当前类的包名,0代表是获取版本信息 8. PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0); 9.return packInfo.versionName; 10.}
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 获取服务器端的版本号: 1./* 2. * 用pull解析器解析服务器返回的xml文件 (xml封装了版本号) 3. */ 4.publicstatic UpdataInfo getUpdataInfo(InputStream is)throws Exception{ 5. XmlPullParser parser = Xml.newPullParser(); 6. parser.setInput(is,"utf-8");//设置解析的数据源 7.int type = parser.getEventType(); 8. UpdataInfo info =new UpdataInfo();//实体 9.while(type != XmlPullParser.END_DOCUMENT ){ 10.switch (type) { 11.case XmlPullParser.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.return info; 24.}
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 从服务器下载apk: 1.publicstatic File getFileFromServer(String path, ProgressDialog pd)throws Exception{ 2.//如果相等的话表示当前的sdcard挂载在手机上并且是可用的 3.if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ 4. URL url =new URL(path); 5. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 6. conn.setConnectTimeout(5000); 7.//获取到文件的大小 8. pd.setMax(conn.getContentLength()); 9. InputStream is = conn.getInputStream(); 10. File file =new File(Environment.getExternalStorageDirectory(),"updata.apk"); 11. FileOutputStream fos =new FileOutputStream(file); 12. BufferedInputStream bis =new BufferedInputStream(is); 13.byte[] buffer =new byte[1024]; 14.int len ; 15.int total=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.return file; 26. } 27.else{ 28.return null; 29. } 30.}

匹配、下载、自动安装:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 /* * 从服务器获取xml解析并进行比对版本号 */ publicclass CheckVersionTaskimplements Runnable{ publicvoid 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(); } } }
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Handler handler =new Handler(){ @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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 /* * * 弹出对话框通知用户更新程序 * * 弹出对话框的步骤: * 1.创建alertDialog的builder. * 2.要给builder设置属性, 对话框的内容,样式,按钮 * 3.通过builder 创建一个对话框 * 4.对话框show()出来 */ protectedvoid showUpdataDialog() { AlertDialog.Builder builer =new Builder(this) ; builer.setTitle("版本升级"); builer.setMessage(info.getDescription()); //当点确定按钮时从服务器上下载 新的apk 然后安装 builer.setPositiveButton("确定",new OnClickListener() { publicvoid onClick(DialogInterface dialog,int which) { Log.i(TAG,"下载apk,更新"); downLoadApk(); } }); //当点取消按钮时进行登录 builer.setNegativeButton("取消",new OnClickListener() { publicvoid onClick(DialogInterface dialog,int which) { // TODO Auto-generated method stub LoginMain(); } }); AlertDialog dialog = builer.create(); dialog.show(); }
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 /* * 从服务器中下载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 =new Message(); msg.what = DOWN_ERROR; handler.sendMessage(msg); e.printStackTrace(); } }}.start(); }
?
1 2 3 4 5 6 7 8 9 //安装apk protectedvoid installApk(File file) { Intent intent =new Intent(); //执行动作 intent.setAction(Intent.ACTION_VIEW); //执行的数据类型 intent.setDataAndType(Uri.fromFile(file),"application/vnd.Android.package-archive");//编者按:此处Android应为android,否则造成安装不了 startActivity(intent); }
?
1 2 3 4 5 6 7 8 9 /* * 进入程序的主界面 */ privatevoid LoginMain(){ Intent intent =new Intent(this,MainActivity.class); startActivity(intent); //结束掉当前的activity this.finish(); }

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

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

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

?
1 2 3 4 <intent-filter> <actionandroid:name="android.intent.action.VIEW"/> <categoryandroid:name="android.intent.category.DEFAULT"/> </intent-filter>

,其实不是;

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


更多相关文章

  1. Android(安卓)定位的实现
  2. Java乔晓松-android中获取手机视频的缩略图
  3. Android中dip(dp)与px之间单位转换 dip2px dp转px 无context算法
  4. 使用FileProvider共享文件
  5. getDrawable()缓存带来的问题
  6. android获取Mac地址和IP地址
  7. Android获取assets文件夹中的数据并写入SD卡示例
  8. android定位
  9. Android——api阅读记录

随机推荐

  1. 转:android实现发送短信并保存到数据库,同
  2. android如何调用dotnet编写的webservice
  3. android选项卡
  4. gradle使用技巧之全局变量
  5. Android设置Proxy访问网络
  6. Android常用布局(FrameLayout、LinearLayo
  7. android studio 如何打包jar(细节)
  8. Android(安卓)实现中文按拼音排序方法
  9. Android和H5、JS进行交互调用
  10. Android Studio自带的多渠道打包简单使用