android 自动检测更新,下载,安装

<pre class="brush:java;toolbar:false">importjava.io.BufferedReader; /** *更新功能模块 * *@authorAdministrator * */ publicclassUpdateManage{ privateContextmContext; //返回的安装包url privateStringapkUrl=&quot;&quot;; privateDialognoticeDialog; privateDialogdownloadDialog; //下载包安装路径 privatestaticfinalStringsavePath=&quot;/sdcard/update/&quot;; privatestaticStringsaveFileName=savePath+&quot;UpdateRelease.apk&quot;; //进度条与通知ui刷新的handler和msg常量 privateProgressBarmProgress; privateTextViewupdate_progress_text; privatestaticfinalintDOWN_UPDATE=1; privatestaticfinalintDOWN_OVER=2; privatestaticfinalintREQUEST_S=3; privateintprogress; privateThreaddownLoadThread; privatebooleaninterceptFlag=false; privateStringnewVerName=&quot;&quot;;//新版本号 privateStringverName=&quot;&quot;;//当前版本号 //下载文件大小 privateStringapkFileSize; //已下载文件大小 privateStringtmpFileSize; privateHandlerhandler=newHandler(){ publicvoidhandleMessage(android.os.Messagemsg){ switch(msg.what){ caseDOWN_UPDATE: mProgress.setProgress(progress); update_progress_text.setText(tmpFileSize+&quot;/&quot;+apkFileSize); break; caseDOWN_OVER: downloadDialog.dismiss(); installApk(); break; caseREQUEST_S: if(!newVerName.equals(verName)){ showNoticeDialog(); }else{ Toast.makeText(mContext,&quot;当前已是最新版本&quot;,Toast.LENGTH_SHORT) .show(); } break; default: break; } } }; publicUpdateManage(Contextcontext){ this.mContext=context; } /** *获取当前版本号 */ privatevoidgetVersion(){ try{ PackageManagerpm=mContext.getPackageManager(); PackageInfopi; pi=pm.getPackageInfo(mContext.getPackageName(),0); verName=pi.versionName; }catch(NameNotFoundExceptione){ e.printStackTrace(); } } /** *获取服务器端app版本信息 * *@return */ privatevoidgetServerVersion(){ newThread(){ publicvoidrun(){ try{ Stringrespone=Tools.getString(Tools .getInputStream(MyUri.getserverinfo)); JSONObjectjson=newJSONObject(respone); Log.i(&quot;updatemanage&quot;,json.toString()); if(json.getString(&quot;flag&quot;).equals(&quot;true&quot;)){ JSONObjectresult_json=json.getJSONObject(&quot;result&quot;); newVerName=result_json.getString(&quot;version&quot;); apkUrl=result_json.getString(&quot;downurl&quot;); }else{ Toast.makeText(mContext,&quot;获取服务端版本信息失败,请稍候重试!&quot;,1) .show(); } handler.sendEmptyMessage(REQUEST_S); }catch(IOExceptione){ e.printStackTrace(); }catch(JSONExceptione){ e.printStackTrace(); } }; }.start(); } //获取客户端,服务端版本信息 privatevoidVersionComparison(){ getVersion(); getServerVersion(); } //外部接口让主Activity调用 publicvoidcheckUpdateInfo(){ VersionComparison(); } /** *新版本提示dialog */ privatevoidshowNoticeDialog(){ AlertDialog.Builderbuilder=newBuilder(mContext);//先得到构造器 builder.setTitle(&quot;软件版本更新&quot;);//设置标题 builder.setMessage(&quot;有新版本,是否更新!&quot;);//设置内容 builder.setIcon(R.drawable.appiconandroid);//设置图标,图片id即可 builder.setPositiveButton(&quot;下载&quot;,newOnClickListener(){ @Override publicvoidonClick(DialogInterfacedialog,intwhich){ dialog.dismiss(); showDownloadDialog(); } }); builder.setNegativeButton(&quot;以后在说&quot;,newOnClickListener(){ @Override publicvoidonClick(DialogInterfacedialog,intwhich){ dialog.dismiss(); } }); noticeDialog=builder.create(); noticeDialog.show(); } /** *新版本下载的dialog */ privatevoidshowDownloadDialog(){ AlertDialog.Builderbuilder=newBuilder(mContext); builder.setTitle(&quot;正在下载中...&quot;); //加载进度条布局 LayoutInflaterinflater=LayoutInflater.from(mContext); Viewv=inflater.inflate(R.layout.update_manage_progress,null); mProgress=(ProgressBar)v.findViewById(R.id.update_progress); update_progress_text=(TextView)v .findViewById(R.id.update_progress_text); builder.setView(v); builder.setNegativeButton(&quot;取消&quot;,newOnClickListener(){ @Override publicvoidonClick(DialogInterfacedialog,intwhich){ dialog.dismiss(); interceptFlag=true; } }); downloadDialog=builder.create(); downloadDialog.show(); downloadApk();//下载apk } privateRunnablemdownloadApkRunnable=newRunnable(){ @Override publicvoidrun(){ try{ URLurl=newURL(apkUrl); HttpURLConnectionconn=(HttpURLConnection)url .openConnection(); conn.setRequestMethod(&quot;GET&quot;); conn.setConnectTimeout(6*1000); conn.setReadTimeout(5000); intlength=conn.getContentLength(); InputStreamis=conn.getInputStream();//得到返回的输入流 //创建apk下载路径文件夹 Filefile=newFile(savePath); if(!file.exists()){ file.mkdirs(); } //创建下载的apk文件,如果没有该文件,写入的时候自动创建 StringapkFile=saveFileName; FileApkFile=newFile(apkFile); FileOutputStreamfos=newFileOutputStream(ApkFile); intcount=0; bytebuf[]=newbyte[1024]; //显示文件大小格式:2个小数点显示 DecimalFormatdf=newDecimalFormat(&quot;0.00&quot;); //进度条下面显示的总文件大小 apkFileSize=df.format((float)length/1024/1024)+&quot;MB&quot;; do{ intnumread=is.read(buf); count+=numread; //进度条下面显示的当前下载文件大小 tmpFileSize=df.format((float)count/1024/1024)+&quot;MB&quot;; //当前进度值 progress=(int)(((float)count/length)*100); //更新进度 handler.sendEmptyMessage(DOWN_UPDATE); if(numread&lt;=0){ //下载完成通知安装 handler.sendEmptyMessage(DOWN_OVER); } fos.write(buf,0,numread); }while(!interceptFlag); fos.close(); is.close(); }catch(MalformedURLExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } } }; /** *下载apk * */ privatevoiddownloadApk(){ downLoadThread=newThread(mdownloadApkRunnable); downLoadThread.start(); } /** *安装apk */ privatevoidinstallApk(){ FileapkFile=newFile(saveFileName); if(!apkFile.exists()){ return; } Intenti=newIntent(Intent.ACTION_VIEW); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setDataAndType(Uri.parse(&quot;file://&quot;+apkFile.toString()), &quot;application/vnd.android.package-archive&quot;); mContext.startActivity(i); android.os.Process.killProcess(android.os.Process.myPid()); }; }</pre><p>update_manage_progress.xml布局</p><pre class="brush:xml;toolbar:false">&lt;?xmlversion=&quot;1.0&quot;encoding=&quot;utf-8&quot;?&gt; &lt;LinearLayoutxmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;vertical&quot;&gt; &lt;ProgressBar android:id=&quot;@+id/update_progress&quot; style=&quot;?android:attr/progressBarStyleHorizontal&quot; android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot;/&gt; &lt;TextView android:id=&quot;@+id/update_progress_text&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_gravity=&quot;right&quot; android:layout_margin=&quot;10dp&quot; android:text=&quot;&quot;/&gt; &lt;/LinearLayout&gt;</pre><p>在需要检测版本更新的地方,调用此方法</p><p>// 检查版本更新</p><p> UpdateManage update = new UpdateManage(MysetActivity.this);</p><p> update.checkUpdateInfo();</p><p>在安装方法installApk()中:</p><p>如果没有android.os.Process.killProcess(android.os.Process.myPid());最后不会提示完成、打开。</p><p>如果没有i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这一步的话,最后安装好了,点打开,是不会打开新版本应用的。</p>
RangeTime:0.010984s
RangeMem:211.58 KB
返回顶部 留言