步骤:
1.检测当前版本的信息AndroidManifest.xml–>manifest–>android:versionName。
2.从服务器获取版本号(版本号存在于xml文件中)并与当前检测到的版本进行匹配,如果不匹配,提示用户进行升级,如果匹配则进入程序主界面。
3.当提示用户进行版本升级时,如果用户点击了确定,系统将自动从服务器上下载并进行自动升级,如果点击取消将进入程序主界面。
效果图:
获取当前程序的版本号:
-
-
-
- private String getVersionName() throws Exception{
-
- PackageManager packageManager = getPackageManager();
-
- PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
- return packInfo.versionName;
- }
/*</p><p> * 获取当前程序的版本号 </p><p> */</p><p> private String getVersionName() throws Exception{</p><p> //获取packagemanager的实例 </p><p> PackageManager packageManager = getPackageManager();</p><p> //getPackageName()是你当前类的包名,0代表是获取版本信息</p><p> PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);</p><p> return packInfo.versionName; </p><p> }
获取服务器端的版本号:
-
-
-
- public static UpdataInfo getUpdataInfo(InputStream is) throws Exception{
- XmlPullParser parser = Xml.newPullParser();
- parser.setInput(is, “utf-8”);
- int type = parser.getEventType();
- UpdataInfo info = new UpdataInfo();
- while(type != XmlPullParser.END_DOCUMENT ){
- switch (type) {
- case XmlPullParser.START_TAG:
- if(“version”.equals(parser.getName())){
- info.setVersion(parser.nextText());
- }else if (“url”.equals(parser.getName())){
- info.setUrl(parser.nextText());
- }else if (“description”.equals(parser.getName())){
- info.setDescription(parser.nextText());
- }
- break;
- }
- type = parser.next();
- }
- return info;
- }
/*</p><p> * 用pull解析器解析服务器返回的xml文件 (xml封装了版本号)</p><p> */</p><p> public static UpdataInfo getUpdataInfo(InputStream is) throws Exception{</p><p> XmlPullParser parser = Xml.newPullParser(); </p><p> parser.setInput(is, "utf-8");//设置解析的数据源 </p><p> int type = parser.getEventType();</p><p> UpdataInfo info = new UpdataInfo();//实体</p><p> while(type != XmlPullParser.END_DOCUMENT ){</p><p> switch (type) {</p><p> case XmlPullParser.START_TAG:</p><p> if("version".equals(parser.getName())){</p><p> info.setVersion(parser.nextText()); //获取版本号</p><p> }else if ("url".equals(parser.getName())){</p><p> info.setUrl(parser.nextText()); //获取要升级的APK文件</p><p> }else if ("description".equals(parser.getName())){</p><p> info.setDescription(parser.nextText()); //获取该文件的信息</p><p> }</p><p> break;</p><p> }</p><p> type = parser.next();</p><p> }</p><p> return info;</p><p> }
从服务器下载apk:
- public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{
-
- if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(5000);
-
- pd.setMax(conn.getContentLength());
- InputStream is = conn.getInputStream();
- File file = new File(Environment.getExternalStorageDirectory(), “updata.apk”);
- FileOutputStream fos = new FileOutputStream(file);
- BufferedInputStream bis = new BufferedInputStream(is);
- byte[] buffer = new byte[1024];
- int len ;
- int total=0;
- while((len =bis.read(buffer))!=-1){
- fos.write(buffer, 0, len);
- total+= len;
-
- pd.setProgress(total);
- }
- fos.close();
- bis.close();
- is.close();
- return file;
- }
- else{
- return null;
- }
- }
public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{</p><p> //如果相等的话表示当前的sdcard挂载在手机上并且是可用的</p><p> if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){</p><p> URL url = new URL(path);</p><p> HttpURLConnection conn = (HttpURLConnection) url.openConnection();</p><p> conn.setConnectTimeout(5000);</p><p> //获取到文件的大小 </p><p> pd.setMax(conn.getContentLength());</p><p> InputStream is = conn.getInputStream();</p><p> File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");</p><p> FileOutputStream fos = new FileOutputStream(file);</p><p> BufferedInputStream bis = new BufferedInputStream(is);</p><p> byte[] buffer = new byte[1024];</p><p> int len ;</p><p> int total=0;</p><p> while((len =bis.read(buffer))!=-1){</p><p> fos.write(buffer, 0, len);</p><p> total+= len;</p><p> //获取当前下载量</p><p> pd.setProgress(total);</p><p> }</p><p> fos.close();</p><p> bis.close();</p><p> is.close();</p><p> return file;</p><p> }</p><p> else{</p><p> return null;</p><p> }</p><p> }
匹配、下载、自动安装:
-
-
-
- public class CheckVersionTask implements Runnable{
-
- public void run() {
- try {
-
- String path = getResources().getString(R.string.serverurl);
-
- 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();
- }
- }
- }
-
- Handler handler = new Handler(){
-
- @Override
- public void handleMessage(Message msg) {
-
- super.handleMessage(msg);
- switch (msg.what) {
- case UPDATA_CLIENT:
-
- showUpdataDialog();
- break;
- case GET_UNDATAINFO_ERROR:
-
- Toast.makeText(getApplicationContext(), “获取服务器更新信息失败”, 1).show();
- LoginMain();
- break;
- case DOWN_ERROR:
-
- Toast.makeText(getApplicationContext(), “下载新版本失败”, 1).show();
- LoginMain();
- break;
- }
- }
- };
-
-
-
-
-
-
-
-
-
-
-
- protected void showUpdataDialog() {
- AlertDialog.Builder builer = new Builder(this) ;
- builer.setTitle(“版本升级”);
- builer.setMessage(info.getDescription());
-
- builer.setPositiveButton(“确定”, new OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- Log.i(TAG,“下载apk,更新”);
- downLoadApk();
- }
- });
-
- builer.setNegativeButton(“取消”, new OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
-
- LoginMain();
- }
- });
- AlertDialog dialog = builer.create();
- dialog.show();
- }
-
-
-
-
- protected void downLoadApk() {
- final ProgressDialog pd;
- pd = new ProgressDialog(this);
- pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- pd.setMessage(“正在下载更新”);
- pd.show();
- new Thread(){
- @Override
- public void 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();
- }
-
-
- protected void installApk(File file) {
- Intent intent = new Intent();
-
- intent.setAction(Intent.ACTION_VIEW);
-
- intent.setDataAndType(Uri.fromFile(file), “application/vnd.android.package-archive”);
- startActivity(intent);
- }
-
-
-
-
- private void LoginMain(){
- Intent intent = new Intent(this,MainActivity.class);
- startActivity(intent);
-
- this.finish();
- }
/*</p><p> * 从服务器获取xml解析并进行比对版本号 </p><p> */</p><p> public class CheckVersionTask implements Runnable{</p><p> public void run() {</p><p> try {</p><p> //从资源文件获取服务器 地址 </p><p> String path = getResources().getString(R.string.serverurl);</p><p> //包装成url的对象 </p><p> URL url = new URL(path);</p><p> HttpURLConnection conn = (HttpURLConnection) url.openConnection(); </p><p> conn.setConnectTimeout(5000);</p><p> InputStream is =conn.getInputStream(); </p><p> info = UpdataInfoParser.getUpdataInfo(is);</p><p> </p><p> if(info.getVersion().equals(versionname)){</p><p> Log.i(TAG,"版本号相同无需升级");</p><p> LoginMain();</p><p> }else{</p><p> Log.i(TAG,"版本号不同 ,提示用户升级 ");</p><p> Message msg = new Message();</p><p> msg.what = UPDATA_CLIENT;</p><p> handler.sendMessage(msg);</p><p> }</p><p> } catch (Exception e) {</p><p> // 待处理 </p><p> Message msg = new Message();</p><p> msg.what = GET_UNDATAINFO_ERROR;</p><p> handler.sendMessage(msg);</p><p> e.printStackTrace();</p><p> } </p><p> }</p><p> }</p><p> </p><p> Handler handler = new Handler(){</p><p> </p><p> @Override</p><p> public void handleMessage(Message msg) {</p><p> // TODO Auto-generated method stub</p><p> super.handleMessage(msg);</p><p> switch (msg.what) {</p><p> case UPDATA_CLIENT:</p><p> //对话框通知用户升级程序 </p><p> showUpdataDialog();</p><p> break;</p><p> case GET_UNDATAINFO_ERROR:</p><p> //服务器超时 </p><p> Toast.makeText(getApplicationContext(), "获取服务器更新信息失败", 1).show();</p><p> LoginMain();</p><p> break; </p><p> case DOWN_ERROR:</p><p> //下载apk失败</p><p> Toast.makeText(getApplicationContext(), "下载新版本失败", 1).show();</p><p> LoginMain();</p><p> break; </p><p> }</p><p> }</p><p> };</p><p> </p><p> /*</p><p> * </p><p> * 弹出对话框通知用户更新程序 </p><p> * </p><p> * 弹出对话框的步骤:</p><p> * 1.创建alertDialog的builder. </p><p> * 2.要给builder设置属性, 对话框的内容,样式,按钮</p><p> * 3.通过builder 创建一个对话框</p><p> * 4.对话框show()出来 </p><p> */</p><p> protected void showUpdataDialog() {</p><p> AlertDialog.Builder builer = new Builder(this) ; </p><p> builer.setTitle("版本升级");</p><p> builer.setMessage(info.getDescription());</p><p> //当点确定按钮时从服务器上下载 新的apk 然后安装 </p><p> builer.setPositiveButton("确定", new OnClickListener() {</p><p> public void onClick(DialogInterface dialog, int which) {</p><p> Log.i(TAG,"下载apk,更新");</p><p> downLoadApk();</p><p> } </p><p> });</p><p> //当点取消按钮时进行登录</p><p> builer.setNegativeButton("取消", new OnClickListener() {</p><p> public void onClick(DialogInterface dialog, int which) {</p><p> // TODO Auto-generated method stub</p><p> LoginMain();</p><p> }</p><p> });</p><p> AlertDialog dialog = builer.create();</p><p> dialog.show();</p><p> }</p><p> </p><p> /*</p><p> * 从服务器中下载APK</p><p> */</p><p> protected void downLoadApk() {</p><p> final ProgressDialog pd; //进度条对话框</p><p> pd = new ProgressDialog(this);</p><p> pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);</p><p> pd.setMessage("正在下载更新");</p><p> pd.show();</p><p> new Thread(){</p><p> @Override</p><p> public void run() {</p><p> try {</p><p> File file = DownLoadManager.getFileFromServer(info.getUrl(), pd);</p><p> sleep(3000);</p><p> installApk(file);</p><p> pd.dismiss(); //结束掉进度条对话框</p><p> } catch (Exception e) {</p><p> Message msg = new Message();</p><p> msg.what = DOWN_ERROR;</p><p> handler.sendMessage(msg);</p><p> e.printStackTrace();</p><p> }</p><p> }}.start();</p><p> }</p><p> </p><p> //安装apk </p><p> protected void installApk(File file) {</p><p> Intent intent = new Intent();</p><p> //执行动作</p><p> intent.setAction(Intent.ACTION_VIEW);</p><p> //执行的数据类型</p><p> intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");</p><p> startActivity(intent);</p><p> }</p><p> </p><p> /*</p><p> * 进入程序的主界面</p><p> */</p><p> private void LoginMain(){</p><p> Intent intent = new Intent(this,MainActivity.class);</p><p> startActivity(intent);</p><p> //结束掉当前的activity </p><p> this.finish();</p><p> }
UpdataInfo:
- public class UpdataInfo {
- private String version;
- private String url;
- private String description;
- public String getVersion() {
- return version;
- }
- public void setVersion(String version) {
- this.version = version;
- }
- public String getUrl() {
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- }
public class UpdataInfo {</p><p> private String version;</p><p> private String url;</p><p> private String description;</p><p> public String getVersion() {</p><p> return version;</p><p> }</p><p> public void setVersion(String version) {</p><p> this.version = version;</p><p> }</p><p> public String getUrl() {</p><p> return url;</p><p> }</p><p> public void setUrl(String url) {</p><p> this.url = url;</p><p> }</p><p> public String getDescription() {</p><p> return description;</p><p> }</p><p> public void setDescription(String description) {</p><p> this.description = description;</p><p> }</p><p>}
update.xml:
- <?xml version=“1.0” encoding=“utf-8”?>
- <info>
- <version>2.0</version>
- <url>http://192.168.1.187:8080/mobilesafe.apk</url>
- <description>检测到最新版本,请及时更新!</description>
- </info>
<?xml version="1.0" encoding="utf-8"?></p><p><info></p><p> <version>2.0</version></p><p> <url>http://192.168.1.187:8080/mobilesafe.apk</url></p><p> <description>检测到最新版本,请及时更新!</description></p><p></info>
来源URL:http://blog.csdn.net/furongkang/article/details/6886526