思路:1在服务器固定目录存放固定的了版本文件;

2.应用请求服务器端的版本文件,判断是否有最新版本;

   3.创建下载连接,下载最新apk;

importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importorg.xmlpull.v1.XmlPullParser;importorg.xmlpull.v1.XmlPullParserException;importandroid.annotation.SuppressLint;importandroid.app.AlertDialog;importandroid.app.AlertDialog.Builder;importandroid.app.DownloadManager;importandroid.app.DownloadManager.Request;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.DialogInterface;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.content.pm.PackageInfo;importandroid.content.pm.PackageManager.NameNotFoundException;importandroid.database.Cursor;importandroid.net.Uri;importandroid.os.Environment;importandroid.os.Handler;importandroid.util.Xml;/***Createdbyshijianon15-8-13.*检查应用版本*/publicclassCheckVersionUtil{publicvoidcheckVersion(Contextcontext){this.context=context;threadPool.execute(checkVersion);}/***检查版本线程*@authorshijian*/RunnablecheckVersion=newRunnable(){@Overridepublicvoidrun(){try{//从清单文件中获得当前版本号PackageInfoinfo=context.getPackageManager().getPackageInfo("cn.com.shijian.test",0);floatlocalVersion=Float.valueOf(info.versionName);floatserverVersion=0;//版本文件在服务器上的路径StringversionPath=CommonUtil.prefixUrl+File.separator+context.getString(R.string.apkversionUrl);URLurl=newURL(versionPath);HttpURLConnectionconn=(HttpURLConnection)url.openConnection();//读入XML文件输入流InputStreaminput=conn.getInputStream();//解析XML文件XmlPullParserparser=Xml.newPullParser();try{parser.setInput(input,"utf-8");inteventType=parser.getEventType();while(eventType!=XmlPullParser.END_DOCUMENT){switch(eventType){caseXmlPullParser.START_TAG://版本if("version".equals(parser.getName())){serverVersion=Float.valueOf(parser.nextText());}//是否强制更新if("ismustupdate".equals(parser.getName())){ismustupdate=parser.nextText();}if("description".equals(parser.getName())){//换行description=parser.nextText().replace("\\n","\n");}break;}eventType=parser.next();}//如果服务器版本号大于本地版本号if(serverVersion>localVersion){booleanpost=handler.post(newRunnable(){@Overridepublicvoidrun(){Builderbuilder=newBuilder(context);builder.setTitle("版本升级");builder.setMessage(description);builder.setPositiveButton("下载最新版",newDialogInterface.OnClickListener(){@OverridepublicvoidonClick(DialogInterfacedialog,intwhich){downloadApk();}});if("1".equals(ismustupdate)){builder.setNegativeButton("取消",newDialogInterface.OnClickListener(){@OverridepublicvoidonClick(DialogInterfacedialog,intwhich){dialog.dismiss();}});}AlertDialogdialog=builder.create();dialog.show();}});//当前版本是最新版}elseif(serverVersion<=localVersion){if(context.getClass().equals(HomeActivity.class)){return;}handler.post(newRunnable(){publicvoidrun(){AlertDialog.Builderbuilder=newBuilder(context);builder.setTitle("版本升级");builder.setMessage("已经是最新版本");AlertDialogdialog=builder.create();dialog.show();}});}}catch(XmlPullParserExceptione){e.printStackTrace();}}catch(NameNotFoundExceptione){e.printStackTrace();}catch(MalformedURLExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}finally{threadPool.shutdown();}}};/****点击下载apk*@authorshijian*@since2015-8-13*/publicvoiddownloadApk(){//获得DownloadManagerfinalDownloadManagerdownloadMgr=(DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);//定义下载URIUriapkLocation=Uri.parse(CommonUtil.prefixUrl+File.separator+context.getString(R.string.apkUrl));Requestrequest=newRequest(apkLocation);//request.setAllowedNetworkTypes(Request.NETWORK_WIFI);request.setTitle("e车问更新");//如果文件件不存在则建立Filefolder=Environment.getExternalStoragePublicDirectory("echewen");if(folder.exists()&&folder.isDirectory()){}else{folder.mkdirs();}//如果echewen.apk已经存在删除掉,防止出现多个Fileapk=newFile(CheckVersionUtil.APK_UPDATE);if(apk.exists()){apk.delete();}//保存下载的文件到指定目录下request.setDestinationInExternalPublicDir("echewen","echewen.apk");//该downloadmanager的IDfinallongref=downloadMgr.enqueue(request);IntentFilterfilter=newIntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);BroadcastReceiverreceiver=newBroadcastReceiver(){@OverridepublicvoidonReceive(Contextcontext,Intentintent){longmRef=intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);if(mRef==ref){Cursorc=downloadMgr.query(newDownloadManager.Query().setFilterById(mRef));c.moveToFirst();StringdownloadFile=c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));IntentinstallIntent=newIntent(Intent.ACTION_VIEW);installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);installIntent.setDataAndType(Uri.parse(downloadFile),"application/vnd.android.package-archive");//设置intent的数据类型context.startActivity(installIntent);}}};context.registerReceiver(receiver,filter);}//线程池ExecutorServicethreadPool=Executors.newCachedThreadPool();Handlerhandler=newHandler();//版本升级说明Stringdescription;//上下文Contextcontext;Stringismustupdate="0";//0:必须更新;1:不必须publicstaticfinalStringAPK_UPDATE=Environment.getExternalStorageDirectory().getPath()+"/echewen/echewen.apk";publicstaticfinalStringSTORAGE_IMAGE_PATH=Environment.getExternalStorageDirectory().getPath()+"/echewen/apk/";}