内容简介:
上一篇讲解了Handler的基本原理和用法,本篇再给出一个实例。
直接看代码:
public class MyAboutActivity extends Activity {
public ProgressDialog mProgressDialog;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_about);
Dialog dialog = new AlertDialog.Builder(MyAboutActivity.this)
.setTitle("应用升级").
setMessage("发现新版本,请升级!")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
mProgressDialog = new ProgressDialog(MyAboutActivity.this);
mProgressDialog.setTitle("正在升级中");
mProgressDialog.setMessage("请稍候...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
downFile("http://localhost:8080/test/apk/test1.apk");
}
}).setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
//do your something
}
}).create();
dialog.show();
}
private void downFile(final String url) {
mProgressDialog.show();
new Thread() {
public void run() {
HttpClient client = new DefaultHttpClient();
//代表连接的url
HttpGet get = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(Environment.getExternalStorageDirectory(), "test1.apk");
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
count += ch;
if (length > 0) {
}
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
downLoadApk();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
private void downLoadApk() {
mHandler.post(new Runnable() {
public void run() {
mProgressDialog.cancel();
updateApp();
}
});
}
private void updateApp() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/test1.apk")), "application/vnd.android.package-archive");
startActivity(intent);
}
}
说明:
调用流程: 在onCreate, 创建dialog,如果用户点击“确定”,就调用到downFile,然后,downFile ->downLoadApk ->mHandler.post。
本文介绍了如何在Android应用中实现应用升级提示,并通过对话框引导用户进行升级操作。包括创建对话框、处理用户选择、下载升级包以及更新应用的过程。重点展示了使用Handler和线程进行异步下载的方法。
1177

被折叠的 条评论
为什么被折叠?



