AsyncTask异步交互的用法简介

首先定义一个类,继承AsyncTask类,并实现相关方法:

<span style="font-size:18px;">/**
 * @author WJL <span style="color:#ff0000;">第一个泛型:规定doInBackground方法的参数类型,规定AsyncTask.execute方法传递的参数类型
 *         第二个泛型:规定onProgressUpdate方法参数的类型,publishProgress参数类型
 *         第三个泛型:规定doInBackground方法的返回值类型</span>
 */
public class MyAsyncTask extends AsyncTask<String, Double, String> {
	TextView textView;
	 ProgressBar bar;
	/**
	 * @param textView
	 * @param bar 
	 */
	public MyAsyncTask(TextView textView, ProgressBar bar) {
		this.textView=textView;
		this.bar=bar;
	}

	// Runs on the UI thread before doInBackground.
	@Override
	// 运行在主线程,在doInBackground方法之前执行
	protected void onPreExecute() {
		System.out.println("准备联网");
	}

	@Override
	// 运行在子线程,做耗时操作
	// 返回值被onPostExecute接收
	<span style="color:#ff0000;">protected String doInBackground(String... params)</span> {

		String string = "100";

		HttpClient httpClient = new DefaultHttpClient();

		// 做联网请求,得到传递的参数,因为是可变长度的数组,想取第一个参数,所以去角标为0的元素
		HttpGet httpGet = new HttpGet(params[0]);

		try {

			HttpResponse httpResponse = httpClient.execute(httpGet);

			if (httpResponse.getStatusLine().getStatusCode() == 200) {

				HttpEntity httpEntity = httpResponse.getEntity();
				//得到实体里的json
				 string = EntityUtils.toString(httpEntity);
				
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 

		return string;

	}

	// Runs on the UI thread after doInBackground.
	// 运行在主线程,在doInBackground方法之后执行,接收doInBackground方法的返回值</span>
<span style="font-size:18px;">在此方法内更新UI线程中的控件
	<span style="color:#ff0000;">protected void onPostExecute(String result)</span> {

		 System.out.println(result);
		 //更新进度
//		 publishProgress(100d);
	};
	
	

	// 更新进度,运行在主线程上,在publishProgress运行之后
	protected void onProgressUpdate(Double[] values) {
//		System.out.println("执行进度:" + values[0]);
		double r = values[0];
		//向上取整
		double floor = Math.ceil(r );
		
		textView.setText(floor+"");
//		bar.setProgress(double.);
	};

	
	//获取进度
	public void progress(){
		
		/*	// 获取数据总长度
		long contentLength = httpEntity.getContentLength();
		System.out.println(contentLength);
		// 获取网络数据
		InputStream inputStream = httpEntity.getContent();

		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream, "utf-8"));

		char[] buf = new char[1];
        //总读取进度
		int sun = 0;
		//本次读取的进度
        int i;
        StringBuilder buffer=new StringBuilder();
		while ((i = bufferedReader.read(buf)) != -1) {
			
			sun=sun+i;
			double count = (((double)sun / (double)contentLength))*100;
			
             //实时更新进度
			publishProgress(count); 
			buffer.append(new String(buf));
		}

		bufferedReader.close();
		inputStream.close();
       string = buffer.toString();*/
		
		
		
		
	}
	
}</span>

在UI主线程调用(注:创建一个MyAsyncTask对象,只能调用一次excute方法)

<span style="font-size:18px;">public class MainActivity extends Activity {
//	String path="http://169.254.214.171:8080/bwie/city.json";
	String key = "3ac9f31ff66b9746539472887b3799c3";
	// 通过get请求时的接口地址
	String get_path = "http://web.juhe.cn:8080/constellation/getAll?consName=狮子座&type=today&key="
			+ key;
	private TextView textView;
	private ProgressBar bar;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView) findViewById(R.id.textView);
		ProgressBar	bar = (ProgressBar) findViewById(R.id.pro);
		MyAsyncTask myAsyncTask=new MyAsyncTask(textView,bar);
		try {
			
			String string = myAsyncTask.execute(get_path).get();
			textView.setText(string);
			System.out.println(string);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
}</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值