提示:该篇与上一篇软件下载一样,只是该片通过异步任务,上一篇是Handler+Thread
什么是异步任务?
- 逻辑上:以多线程的方式完成的功能需求
- API上:指AsyncTask类
AsyncTask的理解:
- 在没有AsyncTask之前,我们使用Handler+Thread就可以实现异步任务的功能需求
- AsyncTask是对Handler和Thread的封装,使用它编码更整洁,更高效
- AsyncTask封装了ThreadPool,比直接使用Thread效率更高
- AsyncTask简化Handler处理多线程通信的问题
AsyncTask<Params,Progress,Result>
- Params启动任务执行的输入参数,比如http请求的url参数
- Progress后台任务执行的百分比
- Result后天执行任务的最终返回的结果,比如String
•execute(Params... params)
启动任务, 开始任务的执行流程
在doInBackground()执行完后在UIThread中执行,一般用来更新界面•void onPreExecute()在分线程工作开始之前在UIThread中执行,一般用来显示提示视图
•ResultdoInBackground(Params... params)在workerThread中执行,完成任务的主要工作,通常需要较长的时间
•void onPostExecute(Result result)
•publishProgress(Progress... values) : 在分线程中, 发布当前进度•voidonProgressUpdate(Progress... values) : 在主线程中更新进度
public void downlode(View v) {
//启动异步任务
new AsyncTask<Void,Integer,Void>() {
//主线程,显示提示视图
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(TestTaskActivity.this);//创建进度条对话框
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//设置为水平进度条
dialog.show();
//用于保存APK文件的File对象
apkFile = new File(getExternalFilesDir(null),"fanny.apk");
}
//分线程,联网请求
@Override
protected Void doInBackground(Void... params) {
try {
String path = "http://192.168.51.5:8080/web_server/listDemo.apk";
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
int requestCode = connection.getResponseCode();
if (requestCode==200) {
dialog.setMax(connection.getContentLength());
InputStream is = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(apkFile);
byte[] buffer = new byte[1024];
int len =-1;
while ((len=is.read(buffer))!=-1) {
fos.write(buffer, 0, len);
// dialog.incrementProgressBy(len);//分线程能更新UI,通过源码我们发现这个方法里使用了Handler
publishProgress(len);//这是异步任务中所设有的方法,把上面第二个参数设置为Integer,一是因为len是整形,二是因为第二个参数表示的是任务执行百分比,这也是进度
SystemClock.sleep(20);
}
fos.close();
is.close();
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//主线程更新界面
@Override
protected void onPostExecute(Void aVoid) {
dialog.dismiss();
installAPK();
}
<span style="white-space:pre"> </span>//更新UI
@Override
protected void onProgressUpdate(Integer... values) {
dialog.incrementProgressBy(values[0]);
}
}.execute();
}
//启动安装界面
private void installAPK() {
Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
intent.setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive");
startActivity(intent);
}