android中的异步任务

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程
还是以下载并安装最新APK例子

package com.hbk.layoutdemo;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;

/**
 * 
 * @author 黄宝康
 *
 */
public class MainActivity extends Activity {


	private File apkFile;
	private ProgressDialog dialog;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	public void downloadApk(View v) {
		new AsyncTask<Void, Integer, Void>(){
			
			//1. 主线程, 显示提示视图
			@Override
			protected void onPreExecute() {
				dialog = new ProgressDialog(MainActivity.this);
				dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				dialog.show();
				apkFile = new File(getExternalFilesDir(null), "update.apk");
			}

			
			
			//3. 主线程, 更新界面
			@Override
			protected void onPostExecute(Void result) {
				dialog.dismiss();
				installAPK();
			}
			
			//2. 分线程, 联网请求
			@Override
			protected Void doInBackground(Void... params) {
				try {
					//1. 得到连接对象
					String path = "http://192.168.1.14:8080/Web_Server/L04_DataStorage.apk";
					URL url = new URL(path);
					HttpURLConnection connection = (HttpURLConnection) url.openConnection();
					//2. 设置
					//connection.setRequestMethod("GET");
					connection.setConnectTimeout(5000);
					connection.setReadTimeout(10000);
					//3. 连接
					connection.connect();
					//4. 请求并得到响应码200
					int responseCode = connection.getResponseCode();
					if(responseCode==200) {
						//设置dialog的最大进度
						dialog.setMax(connection.getContentLength());
						
						
						//5. 得到包含APK文件数据的InputStream
						InputStream is = connection.getInputStream();
						//6. 创建指向apkFile的FileOutputStream
						FileOutputStream fos = new FileOutputStream(apkFile);
						//7. 边读边写
						byte[] buffer = new byte[1024];
						int len = -1;
						while((len=is.read(buffer))!=-1) {
							fos.write(buffer, 0, len);
							//8. 显示下载进度
							//dialog.incrementProgressBy(len);
							//在分线程中, 发布当前进度
							
							publishProgress(len);
							
							//休息一会(模拟网速慢)
							//Thread.sleep(50);
							SystemClock.sleep(50);
						}
						
						fos.close();
						is.close();
					}
					//9. 下载完成, 关闭, 进入3)
					connection.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
			//在主线程中更新进度(在publishProgress()之后)
			protected  void onProgressUpdate(Integer[] values) {
				dialog.incrementProgressBy(values[0]);
			};
		}.execute();
	}

	/**
	 * 启动安装APK
	 */
	private void installAPK() {
		Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
		intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
		startActivity(intent);
	}
}

学习android中的异步任务,我们需要掌握如下几个API
新建AsyncTask有三个泛型public abstract class AsyncTask<Params, Progress, Result>
根据实际情况传递,空的话,传Void
在项目中需要了解异步任务线程的调用关系,顺序
protected void onPreExecute() {// 调用execute()方法前,一般显示提示视图

protected void onPostExecute(Void result)// 调用execute()之后,一般是做一下UI更新操作

protected Void doInBackground(Void… params)// 分线程去执行联网相关请求

protected final void publishProgress(Progress… values) // 在doInBackground方法中发布进度,这个会触发protected void onProgressUpdate(Integer[] values) 方法
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄宝康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值