zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Android实现检查并下载APK更新、安装APK及获取网络信息的方法

Android安装方法网络下载 实现 获取 信息
2023-06-13 09:15:39 时间

本文所述实例为一个天气预报中的android代码,主要包括了下载和安装APK、检查Apk更新、显示"已经是最新"或者"无法获取版本信息"对话框、获取当前客户端版本信息、显示版本更新通知对话框、显示下载对话框、判断是否挂载了SD卡、显示文件大小格式:2个小数点显示等。具体实现代码如下:

importjava.io.ByteArrayInputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.MalformedURLException;
importjava.net.URL;
importjava.text.DecimalFormat;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.conn.ConnectTimeoutException;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.params.CoreConnectionPNames;
importorg.apache.http.util.EntityUtils;
importorg.lmw.weather.R;
importorg.lmw.weather.entity.AppDetail;
importandroid.app.AlertDialog;
importandroid.app.Dialog;
importandroid.app.ProgressDialog;
importandroid.app.AlertDialog.Builder;
importandroid.content.Context;
importandroid.content.DialogInterface;
importandroid.content.Intent;
importandroid.content.DialogInterface.OnCancelListener;
importandroid.content.DialogInterface.OnClickListener;
importandroid.content.pm.PackageInfo;
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.TextView;
importandroid.widget.Toast;
publicclassDownloadManager{
privatestaticfinalintDOWN_NOSDCARD=0;
privatestaticfinalintDOWN_UPDATE=1;
privatestaticfinalintDOWN_OVER=2;
privatestaticfinalintDOWN_ERROR=3;
privatestaticfinalintDIALOG_TYPE_LATEST=0;
privatestaticfinalintDIALOG_TYPE_FAIL=1;
privatestaticfinalintDIALOG_TYPE_INTERNETERROR=2;
privatestaticDownloadManagerdownloadManager;
privateContextmContext;
//通知对话框
privateDialognoticeDialog;
//下载对话框
privateDialogdownloadDialog;
//进度条
privateProgressBarmProgress;
//显示下载数值
privateTextViewmProgressText;
//查询动画
privateProgressDialogmProDialog;
//"已经是最新"或者"无法获取最新版本"的对话框
privateDialoglatestOrFailDialog;
//返回的安装包url
privateStringapkUrl="";
//进度值
privateintprogress;
//下载线程
privateThreaddownLoadThread;
//终止标记
privatebooleaninterceptFlag;
//提示语
privateStringupdateMsg="";
//下载包保存路径
privateStringsavePath="";
//apk保存完整路径
privateStringapkFilePath="";
//临时下载文件路径
privateStringtmpFilePath="";
//下载文件大小
privateStringapkFileSize;
//已下载文件大小
privateStringtmpFileSize;
privateStringcurVersionName="";
privateintcurVersionCode;
privateAppDetailmDownload;
privateStringcheckUrl="http://192.168.0.133:8080/lmw/androidMarket/SimpleWeather-20130701093349937/update.xml";
privateHandlermHandler=newHandler(){
publicvoidhandleMessage(Messagemsg){
switch(msg.what){
caseDOWN_UPDATE:
mProgress.setProgress(progress);
mProgressText.setText(tmpFileSize+"/"+apkFileSize);
break;
caseDOWN_OVER:
downloadDialog.dismiss();
installApk();
break;
caseDOWN_NOSDCARD:
downloadDialog.dismiss();
Toast.makeText(mContext,"无法下载安装文件,请检查SD卡是否挂载",Toast.LENGTH_SHORT).show();
break;
caseDOWN_ERROR:
downloadDialog.dismiss();
if(msg.arg1==0){
Toast.makeText(mContext,"网络不给力啊",Toast.LENGTH_SHORT).show();
}elseif(msg.arg1==1||msg.arg1==2){
Toast.makeText(mContext,"未找到资源",Toast.LENGTH_SHORT).show();
}
break;
}
};
};
publicstaticDownloadManagergetDownloadManager(){
if(downloadManager==null){
downloadManager=newDownloadManager();
}
downloadManager.interceptFlag=false;
returndownloadManager;
}
publicvoidDownLoader(Contextcontext,AppDetaildownload){
this.mContext=context;
this.mDownload=download;
showDownloadDialog();
}
/**
*检查App更新
*@paramcontext
*@paramisShowMsg
*是否显示提示消息
*/
publicvoidcheckAppUpdate(Contextcontext,finalbooleanisShowMsg,finalbooleannotmain){
this.mContext=context;
getCurrentVersion(mContext);
if(isShowMsg){
if(mProDialog==null)
mProDialog=ProgressDialog.show(mContext,null,"正在检测,请稍后...",true,true);
elseif(mProDialog.isShowing()||(latestOrFailDialog!=null&&latestOrFailDialog.isShowing()))
return;
}
finalHandlerhandler=newHandler(){
publicvoidhandleMessage(Messagemsg){
//进度条对话框不显示-检测结果也不显示
if(mProDialog!=null&&!mProDialog.isShowing()){
return;
}
//关闭并释放释放进度条对话框
if(isShowMsg&&mProDialog!=null){
mProDialog.dismiss();
mProDialog=null;
}
//显示检测结果
if(msg.what==1){
mDownload=(AppDetail)msg.obj;
if(mDownload!=null){
if(curVersionCode<mDownload.getVersionCode()){
apkUrl=mDownload.getUri()+mDownload.getFileName();
updateMsg=mDownload.getAppHistory();
showNoticeDialog();
}elseif(isShowMsg){
if(notmain){
showLatestOrFailDialog(DIALOG_TYPE_LATEST);
}
}
}
}elseif(msg.what==-1&&isShowMsg){
showLatestOrFailDialog(DIALOG_TYPE_INTERNETERROR);
}elseif(isShowMsg){
showLatestOrFailDialog(DIALOG_TYPE_FAIL);
}
}
};
newThread(){
publicvoidrun(){
Messagemsg=newMessage();
try{
DefaultHttpClientclient=newDefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,3000);
HttpGetget=newHttpGet(checkUrl);
HttpResponseresponse=client.execute(get);
if(response.getStatusLine().getStatusCode()==200){
HttpEntityentity=response.getEntity();
InputStreamstream=newByteArrayInputStream(EntityUtils.toString(entity,"gb2312").getBytes());
AppDetailupdate=AppDetail.parseXML(stream);
msg.what=1;
msg.obj=update;
}else{
msg.what=-1;
}
}catch(Exceptione){
e.printStackTrace();
msg.what=-1;
}
handler.sendMessage(msg);
}
}.start();
}
/*显示"已经是最新"或者"无法获取版本信息"对话框*/
privatevoidshowLatestOrFailDialog(intdialogType){
StringToastMsg="";
if(latestOrFailDialog!=null){
//关闭并释放之前的对话框
latestOrFailDialog.dismiss();
latestOrFailDialog=null;
}
//AlertDialog.Builderbuilder=newBuilder(mContext);
//builder.setTitle("系统提示");
if(dialogType==DIALOG_TYPE_LATEST){
//builder.setMessage("您当前已经是最新版本");
ToastMsg="您当前已经是最新版本";
}elseif(dialogType==DIALOG_TYPE_FAIL){
//builder.setMessage("无法获取版本更新信息");
ToastMsg="无法获取版本更新信息";
}elseif(dialogType==DIALOG_TYPE_INTERNETERROR){
//builder.setMessage("网络故障,无法连接服务器");
ToastMsg="网络故障,无法连接服务器";
}
Toast.makeText(mContext,ToastMsg,Toast.LENGTH_SHORT).show();
}
/*获取当前客户端版本信息*/
publicStringgetCurrentVersion(Contextcontext){
try{
PackageInfoinfo=context.getPackageManager().getPackageInfo(context.getPackageName(),0);
curVersionName=info.versionName;
curVersionCode=info.versionCode;
}catch(NameNotFoundExceptione){
e.printStackTrace(System.err);
}
returncurVersionName;
}
/*显示版本更新通知对话框*/
privatevoidshowNoticeDialog(){
AlertDialog.Builderbuilder=newBuilder(mContext);
builder.setTitle("软件版本更新");
builder.setMessage(updateMsg);
builder.setPositiveButton("立即更新",newOnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
dialog.dismiss();
showDownloadDialog();
}
});
builder.setNegativeButton("以后再说",newOnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
dialog.dismiss();
}
});
noticeDialog=builder.create();
noticeDialog.show();
}
/*显示下载对话框*/
privatevoidshowDownloadDialog(){
AlertDialog.Builderbuilder=newBuilder(mContext);
builder.setTitle("正在下载安装包");
finalLayoutInflaterinflater=LayoutInflater.from(mContext);
Viewv=inflater.inflate(R.layout.download_progress,null);
mProgress=(ProgressBar)v.findViewById(R.id.update_progress);
mProgressText=(TextView)v.findViewById(R.id.update_progress_text);
builder.setView(v);
builder.setNegativeButton("取消",newOnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
dialog.dismiss();
interceptFlag=true;
}
});
builder.setOnCancelListener(newOnCancelListener(){
@Override
publicvoidonCancel(DialogInterfacedialog){
dialog.dismiss();
interceptFlag=true;
}
});
downloadDialog=builder.create();
downloadDialog.setCanceledOnTouchOutside(false);
downloadDialog.show();
downloadApk();
}
privateRunnablemdownApkRunnable=newRunnable(){
Messageerror_msg=newMessage();
@Override
publicvoidrun(){
try{
StringapkName=mDownload.getFileName().replace(".apk","")+".apk";
StringtmpApk=mDownload.getFileName().replace(".apk","")+".tmp";
//判断是否挂载了SD卡
StringstorageState=Environment.getExternalStorageState();
if(storageState.equals(Environment.MEDIA_MOUNTED)){
savePath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/QN/QNStore/";
Filefile=newFile(savePath);
if(!file.exists()){
file.mkdirs();
}
apkFilePath=savePath+apkName;
tmpFilePath=savePath+tmpApk;
}
//没有挂载SD卡,无法下载文件
if(apkFilePath==null||apkFilePath==""){
mHandler.sendEmptyMessage(DOWN_NOSDCARD);
return;
}
FileApkFile=newFile(apkFilePath);
//是否已下载更新文件
//if(ApkFile.exists()){
//downloadDialog.dismiss();
//installApk();
//return;
//}
//输出临时下载文件
FiletmpFile=newFile(tmpFilePath);
FileOutputStreamfos=newFileOutputStream(tmpFile);
URLurl=newURL(mDownload.getUri()+mDownload.getFileName());
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
try{
conn.connect();
}catch(ConnectTimeoutExceptione){
error_msg.what=DOWN_ERROR;
error_msg.arg1=0;
mHandler.sendMessage(error_msg);
}
intlength=conn.getContentLength();
InputStreamis=conn.getInputStream();
//显示文件大小格式:2个小数点显示
DecimalFormatdf=newDecimalFormat("0.00");
//进度条下面显示的总文件大小
apkFileSize=df.format((float)length/1024/1024)+"MB";
intcount=0;
bytebuf[]=newbyte[1024];
do{
intnumread=is.read(buf);
count+=numread;
//进度条下面显示的当前下载文件大小
tmpFileSize=df.format((float)count/1024/1024)+"MB";
//当前进度值
progress=(int)(((float)count/length)*100);
//更新进度
mHandler.sendEmptyMessage(DOWN_UPDATE);
if(numread<=0){
//下载完成-将临时下载文件转成APK文件
if(tmpFile.renameTo(ApkFile)){
//通知安装
mHandler.sendEmptyMessage(DOWN_OVER);
}
break;
}
fos.write(buf,0,numread);
}while(!interceptFlag);//点击取消就停止下载
fos.close();
is.close();
}catch(MalformedURLExceptione){
error_msg.what=DOWN_ERROR;
error_msg.arg1=1;
mHandler.sendMessage(error_msg);
e.printStackTrace();
}catch(IOExceptione){
error_msg.what=DOWN_ERROR;
error_msg.arg1=2;
mHandler.sendMessage(error_msg);
e.printStackTrace();
}
}
};
/**
*下载apk
*@paramurl
*/
privatevoiddownloadApk(){
downLoadThread=newThread(mdownApkRunnable);
downLoadThread.start();
}
/**
*安装apk
*@paramurl
*/
privatevoidinstallApk(){
Fileapkfile=newFile(apkFilePath);
if(!apkfile.exists()){
return;
}
Intenti=newIntent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://"+apkfile.toString()),"application/vnd.android.package-archive");
mContext.startActivity(i);
}
}