Android应用程序更新并下载实例
整理文档,搜刮出一个Android应用程序更新并下载实例的代码,稍微整理精简一下做下分享。
创建一个新类,名为UpdateManager,代码如下:
importjava.io.BufferedReader; importjava.io.File; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.net.HttpURLConnection; importjava.net.MalformedURLException; importjava.net.URL; importcom.af.mobile.R; importandroid.app.AlertDialog; importandroid.app.Dialog; importandroid.app.AlertDialog.Builder; importandroid.content.Context; importandroid.content.DialogInterface; importandroid.content.Intent; importandroid.content.DialogInterface.OnClickListener; importandroid.content.pm.PackageManager.NameNotFoundException; importandroid.net.Uri; importandroid.os.Environment; importandroid.os.Handler; importandroid.os.Message; importandroid.view.LayoutInflater; importandroid.view.View; importandroid.widget.ProgressBar; importandroid.widget.Toast; publicclassUpdateManager {privateURLurl=null; /*下载中*/ privatestaticfinalintDOWNLOAD=1; /*下载结束*/ privatestaticfinalintDOWNLOAD_FINISH=2; /*保存解析的XML信息*/ //HashMapmHashMap; /*下载保存路径*/ privateStringmSavePath; /*记录进度条数量*/ privateintprogress; /*是否取消更新*/ privatebooleancancelUpdate=false; privateContextmContext; /*更新进度条*/ privateProgressBarmProgress; privateDialogmDownloadDialog; privateHandlermHandler=newHandler() { publicvoidhandleMessage(Messagemsg) { switch(msg.what) { //正在下载 caseDOWNLOAD: //设置进度条位置 mProgress.setProgress(progress); break; caseDOWNLOAD_FINISH: //安装文件 installApk(); break; default: break; } }; }; publicUpdateManager(Contextcontext) { this.mContext=context; } publicvoidcheckUpdate() { if(isUpdate()) { showNoticeDialog(); }else { } } /** *检查软件是否有更新版本 * *@return */ privatebooleanisUpdate() { //获取当前软件版本 DoubleversionCode=getVersionCode(mContext); DoubleserviceCode=1.2; //版本判断 if(serviceCode>versionCode) { returntrue; } returnfalse; } //获取软件版本号 privateDoublegetVersionCode(Contextcontext) { DoubleversionCode=0.0; try { //获取软件版本号,对应AndroidManifest.xml下android:versionCode versionCode=(double)context.getPackageManager().getPackageInfo("com.af.mobile",0).versionCode; }catch(NameNotFoundExceptione) { e.printStackTrace(); } returnversionCode; } //显示软件更新对话框 privatevoidshowNoticeDialog() { AlertDialog.Builderbuilder=newBuilder(mContext); builder.setTitle("软件更新"); Stringstring=download("http://192.168.0.102:9313/daojuserver/uploads/version.xml");//xml的下载地址 builder.setMessage(string); builder.setPositiveButton("更新",newOnClickListener() { @Override publicvoidonClick(DialogInterfacedialog,intwhich) { dialog.dismiss(); //显示下载对话框 showDownloadDialog(); } }); //稍后更新 builder.setNegativeButton("稍后更新",newOnClickListener() { @Override publicvoidonClick(DialogInterfacedialog,intwhich) { dialog.dismiss(); } }); DialognoticeDialog=builder.create(); noticeDialog.show(); } //显示软件下载对话框 privatevoidshowDownloadDialog() { //构造软件下载对话框 AlertDialog.Builderbuilder=newBuilder(mContext); builder.setTitle("djfkjd");//提示信息内容 //给下载对话框增加进度条 finalLayoutInflaterinflater=LayoutInflater.from(mContext); Viewv=inflater.inflate(R.layout.softupdate_progress,null); mProgress=(ProgressBar)v.findViewById(R.id.update_progress); builder.setView(v); //取消更新 builder.setNegativeButton("取消更新",newOnClickListener() { @Override publicvoidonClick(DialogInterfacedialog,intwhich) { dialog.dismiss(); //设置取消状态 cancelUpdate=true; } }); mDownloadDialog=builder.create(); mDownloadDialog.show(); //现在文件 downloadApk(); } privatevoiddownloadApk() { //启动新线程下载软件 newdownloadApkThread().start(); } privateclassdownloadApkThreadextendsThread { @Override publicvoidrun() { try { //判断SD卡是否存在,并且是否具有读写权限 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //获得存储卡的路径 Stringsdpath=Environment.getExternalStorageDirectory()+"/"; mSavePath=sdpath+"download"; URLurl=newURL("http://192.168.0.102:9313/daojuserver/uploads/SpMobile.apk");//apk下载地址地址 //创建连接 HttpURLConnectionconn=(HttpURLConnection)url.openConnection(); conn.connect(); //获取文件大小 intlength=conn.getContentLength(); //创建输入流 InputStreamis=conn.getInputStream(); Filefile=newFile(mSavePath); if(!file.exists()) { file.mkdir(); } FileapkFile=newFile(mSavePath,"dhfudh"); FileOutputStreamfos=newFileOutputStream(apkFile); intcount=0; //缓存 bytebuf[]=newbyte[1024]; //写入到文件中 do { intnumread=is.read(buf); count+=numread; //计算进度条位置 progress=(int)(((float)count/length)*100); //更新进度 mHandler.sendEmptyMessage(DOWNLOAD); if(numread<=0) { mHandler.sendEmptyMessage(DOWNLOAD_FINISH); break; } fos.write(buf,0,numread); }while(!cancelUpdate); fos.close(); is.close(); } }catch(MalformedURLExceptione) { e.printStackTrace(); }catch(IOExceptione) { e.printStackTrace(); } //取消下载对话框显示 mDownloadDialog.dismiss(); } }; privatevoidinstallApk() { Fileapkfile=newFile(mSavePath,"dhfudh"); if(!apkfile.exists()) { return; } //通过Intent安装APK文件 Intenti=newIntent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("file://"+apkfile.toString()),"application/vnd.android.package-archive"); mContext.startActivity(i); } publicStringdownload(StringurlString) { StringBuffersbBuffer=newStringBuffer(); Stringline=null; BufferedReaderbuffer=null; try{ url=newURL(urlString); HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection(); buffer=newBufferedReader(newInputStreamReader(urlConn.getInputStream())); while((line=buffer.readLine())!=null) { sbBuffer.append(line); } }catch(Exceptione){ //TODO:handleexception e.printStackTrace(); } finally { try{ buffer.close(); }catch(Exceptione2){ //TODO:handleexception e2.printStackTrace(); } } returnsbBuffer.toString(); } }
在Android应用程序Main界面
if(isOpenNetwork())//判断是否有网络 { UpdateManagermanager=newUpdateManager(Main.this); //检查软件更新 manager.checkUpdate(); }
判断移动端是否有网络
privatebooleanisOpenNetwork(){ ConnectivityManagerconnManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfonetworkInfo=connManager.getActiveNetworkInfo(); if(networkInfo!=null){ //2.获取当前网络连接的类型信息 intnetworkType=networkInfo.getType(); if(ConnectivityManager.TYPE_WIFI==networkType){ //当前为wifi网络 }elseif(ConnectivityManager.TYPE_MOBILE==networkType){ //当前为mobile网络 } returnconnManager.getActiveNetworkInfo().isAvailable(); } returnfalse; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。