publicclass MainActivity extends FragmentActivity
{
privatestaticfinalintUPDATA_CLIENT = -2; // 更新版本;
privatestaticfinalintNET_ERROR = -1; // 网络错误;
privatestaticfinalintFILE_SIZE = 0; // 文件的大小;
privatestaticfinalintDOWNLOAD_PROGRESS = 1; // 下载的进度;
privatestaticfinalintDOWNLOAD_FINISHED = 2; // 下载完成;
privatestaticfinalintCANCEL_DOWNLOAD = 3; // 取消下载;
privateintfileSize;
privateintdownLoadFileSize;// 已经下载的文件的大小;
privateRunnable downloadRunnable = null; //下载线程对象;
public Handlerhandler=new Handler()
{
@Override
publicvoid handleMessage(Message msg)
{
switch(msg.what)
{
caseUPDATA_CLIENT://更新版本
showUpdateInterface();
break;
caseNET_ERROR://网络连接错误
Toast.makeText(MainActivity.this, R.string.net_unavailable, Toast.LENGTH_SHORT).show();
break;
caseFILE_SIZE:
progressDialog.setMax(fileSize);//设置最大值
break;
caseDOWNLOAD_PROGRESS:
progressDialog.setProgress(downLoadFileSize);
break;
caseCANCEL_DOWNLOAD://取消下载
this.removeCallbacks(downloadRunnable);
Log.i("run",""+downloadRunnable);
break;
caseDOWNLOAD_FINISHED://下载完成
progressDialog.dismiss();
if(file!=null){
Uri uri=Uri.fromFile(file);
//安装的Intent对象
IntentinstallIntent=new Intent(Intent.ACTION_VIEW);
installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.setDataAndType(uri,"application/vnd.android.package-archive");
startActivity(installIntent);
}
break;
}
}
};
protectedvoid onCreate(Bundle savedInstanceState){
………..
newCheckVersionThread().start();
}
//显示更新对话框
privatevoidshowUpdateInterface()
{
newAlertDialog.Builder(this)
.setTitle(R.string.update_version)
.setMessage(R.string.update_notify)
.setNegativeButton(R.string.cancel,null)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
@Override
publicvoidonClick(DialogInterface dialog,int which) {
myApplication.setUpdateInfo(updateInfo);
showDownloadDialog();
}
}).setCancelable(false).create().show();
}
//显示正在下载的对话框
protectedvoidshowDownloadDialog()
{
if(progressDialog!=null)
{
progressDialog=null;
}
progressDialog=new ProgressDialog(this);
//设置进度条风格,风格为长形
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setIcon(R.drawable.down_ico);
progressDialog.setTitle(R.string.updatesoftware);
progressDialog.setMessage(this.getString(R.string.downloadingbk));
progressDialog.setProgress(100);
//设置ProgressDialog的进度条是否明确
progressDialog.setIndeterminate(false);
//设置ProgressDialog按退回按键取消
progressDialog.setCanceledOnTouchOutside(false);
//让ProgressDialog显示
progressDialog.show();
downloadRunnable=new DownLoadThread();
new Thread(downloadRunnable).start();
}
class DownLoadThreadimplements Runnable
{
@Override
publicvoid run()
{
Looper.prepare();
//设置为正在执行更新
isUpdating=true;
//在新线程里执行长耗时方法
longTimeMethod();
//执行完毕后给handler发送一个空消息
handler.sendEmptyMessage(0);
Looper.loop();
}
privatevoidlongTimeMethod()
{
try
{
URL url11=new URL(updateInfo.getUrl());
HttpURLConnectionconn=(HttpURLConnection)url11.openConnection();
conn.setConnectTimeout(5000);
conn.setDoInput(true);
InputStream inStream=conn.getInputStream();
//设置下载路径
file=new File(getFilesDir(),"xxx.apk");
//如果想把应用下载到SD卡或外部存储卡上时改为:
//Environment.getExternalStorageDirectory()
BufferedInputStream bis=newBufferedInputStream(inStream);
FileOutputStream fos=newFileOutputStream(file);
//文件的长度
fileSize = 100;
sendMsg(FILE_SIZE);
int len=0;
int actualFileSize=conn.getContentLength();
int rate=0;
byte[] buffer=newbyte[1024];
while((len=bis.read(buffer))!=-1)
{
rate+=len;
downLoadFileSize=(int)(((float)rate/actualFileSize)*100);//下载的百分比
fos.write(buffer,0,len);
sendMsg(DOWNLOAD_PROGRESS);
Thread.sleep(20);
}
fos.close();
sendMsg(DOWNLOAD_FINISHED);
}catch (InterruptedException e)
{
handleException();
} catch(MalformedURLException e)
{
handleException();
} catch (IOExceptione)
{
handleException2();
}
}
privatevoid sendMsg(int flag)
{
Message msg=new Message();
msg.what=flag;
handler.sendMessage(msg);
}
}
publicvoidhandleException2()
{
dismissMyDialog();
handler.removeCallbacks(downloadRunnable);
Toast.makeText(MainActivity.this, R.string.downloadfail_oth,0).show();
}
publicvoidhandleException()
{
dismissMyDialog();
handler.removeCallbacks(downloadRunnable);
Toast.makeText(MainActivity.this, R.string.downloadfail,0).show();
}
/*
* 检查版本更新
* 启动新线程
*/
classCheckVersionThread extends Thread
{
@Override
publicvoid run()
{
InputStreaminputStream;
try
{
/*=======此处更改为服务器存放软件版本信息的URL==============*/
String path="http://jfb.9966.org/gkzs/versionInfo.xml";
URL url=new URL(path);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
inputStream=conn.getInputStream();
intcurrentVersion=myApplication.getCurrentVersionCode();
updateInfo=myApplication.getUpdateInfo(inputStream);
if(Integer.parseInt(updateInfo.getVersion())>currentVersion)
{
Message msg=handler.obtainMessage();
msg.what=UPDATA_CLIENT;
handler.sendMessage(msg);
}
}catch(Exception e)
{
Message message=handler.obtainMessage();
message.what=NET_ERROR;
handler.sendMessage(message);
}
}
}
}
MyApplication类中关键代码:
public UpdateInfogetUpdateInfo(InputStreaminStream)throws XmlPullParserException,IOException
{
UpdateInfo updateInfo=null;
XmlPullParserparser=Xml.newPullParser();
parser.setInput(inStream,"utf-8");
inteventType=parser.getEventType();
while(eventType!=XmlPullParser.END_DOCUMENT)
{
switch(eventType)
{
case XmlPullParser.START_DOCUMENT:
updateInfo=new UpdateInfo();
break;
case XmlPullParser.START_TAG:
if("version".equals(parser.getName()))
{
Stringversion=parser.nextText();
updateInfo.setVersion(version);
}elseif("url".equals(parser.getName()))
{
Stringurl=parser.nextText();
updateInfo.setUrl(url);
}elseif("description".equals(parser.getName()))
{
Stringdescription=parser.nextText();
updateInfo.setDescription(description);
}
break;
case XmlPullParser.END_DOCUMENT:
updateInfo=null;
default:
break;
}
eventType=parser.next();
}
returnupdateInfo;
}
注意:需要在AndroidManifest.xml中加以下权限:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />