android应用客户端自动升级
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.impl.client.DefaultHttpClient;
importandroid.app.AlertDialog;
importandroid.app.Dialog;
importandroid.app.ProgressDialog;
importandroid.content.DialogInterface;
importandroid.content.Intent;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.os.Handler;
publicclassUpdateextendsBaseActivity{
publicProgressDialogpBar;
privateHandlerhandler=newHandler();
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.update);
Dialogdialog=newAlertDialog.Builder(Update.this).setTitle("系统更新")
.setMessage("发现新版本,请更新!")//设置内容
.setPositiveButton("确定",//设置确定按钮
newDialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,
intwhich){
pBar=newProgressDialog(Update.this);
pBar.setTitle("正在下载");
pBar.setMessage("请稍候...");
pBar
.setProgressStyle(ProgressDialog.STYLE_SPINNER);
downFile("http://url:8765/OA.apk");
}
}).setNegativeButton("取消",
newDialogInterface.OnClickListener(){
publicvoidonClick(DialogInterfacedialog,
intwhichButton){
//点击"取消"按钮之后退出程序
}
}).create();//创建
//显示对话框
dialog.show();
}
voiddownFile(finalStringurl){
pBar.show();
newThread(){
publicvoidrun(){
HttpClientclient=newDefaultHttpClient();
//params[0]代表连接的url
HttpGetget=newHttpGet(url);
HttpResponseresponse;
try{
response=client.execute(get);
HttpEntityentity=response.getEntity();
longlength=entity.getContentLength();
InputStreamis=entity.getContent();
FileOutputStreamfileOutputStream=null;
if(is!=null){
Filefile=newFile(Environment
.getExternalStorageDirectory(),"OA.apk");
fileOutputStream=newFileOutputStream(file);
byte[]buf=newbyte[1024];
intch=-1;
intcount=0;
while((ch=is.read(buf))!=-1){
//baos.write(buf,0,ch);
fileOutputStream.write(buf,0,ch);
count+=ch;
if(length>0){
}
}
}
fileOutputStream.flush();
if(fileOutputStream!=null){
fileOutputStream.close();
}
down();
}catch(ClientProtocolExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}.start();
}
voiddown(){
handler.post(newRunnable(){
publicvoidrun(){
pBar.cancel();
update();
}
});
}
voidupdate(){
Intentintent=newIntent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(newFile("/sdcard/OA.apk")),
"application/vnd.android.package-archive");
startActivity(intent);
}
}