<pre class="brush:java;toolbar:false">importjava.io.BufferedReader;
/**
*更新功能模块
*
*@authorAdministrator
*
*/
publicclassUpdateManage{
privateContextmContext;
//返回的安装包url
privateStringapkUrl="";
privateDialognoticeDialog;
privateDialogdownloadDialog;
//下载包安装路径
privatestaticfinalStringsavePath="/sdcard/update/";
privatestaticStringsaveFileName=savePath+"UpdateRelease.apk";
//进度条与通知ui刷新的handler和msg常量
privateProgressBarmProgress;
privateTextViewupdate_progress_text;
privatestaticfinalintDOWN_UPDATE=1;
privatestaticfinalintDOWN_OVER=2;
privatestaticfinalintREQUEST_S=3;
privateintprogress;
privateThreaddownLoadThread;
privatebooleaninterceptFlag=false;
privateStringnewVerName="";//新版本号
privateStringverName="";//当前版本号
//下载文件大小
privateStringapkFileSize;
//已下载文件大小
privateStringtmpFileSize;
privateHandlerhandler=newHandler(){
publicvoidhandleMessage(android.os.Messagemsg){
switch(msg.what){
caseDOWN_UPDATE:
mProgress.setProgress(progress);
update_progress_text.setText(tmpFileSize+"/"+apkFileSize);
break;
caseDOWN_OVER:
downloadDialog.dismiss();
installApk();
break;
caseREQUEST_S:
if(!newVerName.equals(verName)){
showNoticeDialog();
}else{
Toast.makeText(mContext,"当前已是最新版本",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("updatemanage",json.toString());
if(json.getString("flag").equals("true")){
JSONObjectresult_json=json.getJSONObject("result");
newVerName=result_json.getString("version");
apkUrl=result_json.getString("downurl");
}else{
Toast.makeText(mContext,"获取服务端版本信息失败,请稍候重试!",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("软件版本更新");//设置标题
builder.setMessage("有新版本,是否更新!");//设置内容
builder.setIcon(R.drawable.appiconandroid);//设置图标,图片id即可
builder.setPositiveButton("下载",newOnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
dialog.dismiss();
showDownloadDialog();
}
});
builder.setNegativeButton("以后在说",newOnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
dialog.dismiss();
}
});
noticeDialog=builder.create();
noticeDialog.show();
}
/**
*新版本下载的dialog
*/
privatevoidshowDownloadDialog(){
AlertDialog.Builderbuilder=newBuilder(mContext);
builder.setTitle("正在下载中...");
//加载进度条布局
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("取消",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("GET");
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("0.00");
//进度条下面显示的总文件大小
apkFileSize=df.format((float)length/1024/1024)+"MB";
do{
intnumread=is.read(buf);
count+=numread;
//进度条下面显示的当前下载文件大小
tmpFileSize=df.format((float)count/1024/1024)+"MB";
//当前进度值
progress=(int)(((float)count/length)*100);
//更新进度
handler.sendEmptyMessage(DOWN_UPDATE);
if(numread<=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("file://"+apkFile.toString()),
"application/vnd.android.package-archive");
mContext.startActivity(i);
android.os.Process.killProcess(android.os.Process.myPid());
};
}</pre><p>update_manage_progress.xml布局</p><pre class="brush:xml;toolbar:false"><?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ProgressBar
android:id="@+id/update_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/update_progress_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_margin="10dp"
android:text=""/>
</LinearLayout></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>