---
title: "Android 异步网络请求及协调CountDownLatch"
author: "sw1982"
date: "2014-03-27T17:43:17Z"
tags: []
categories: ["移动开发"]
slug: "android-countdownlatch"
draft: false
lastmod: "2014-03-27T17:43:16Z"
id: 2037644
url: "https://sw1982.iteye.com/blog/2037644"
---

1.框架

loopj.com/android-async-http/

 

2.使用： 

```
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        System.out.println(response);
    }
});
```

 注意坑：client推荐使用单例，但是不要随便放在class的static里面， 一定要放到application类里面。 否则切出应用2分钟后回来，请求失败了啊。

 

3.返回处理(以json为例,结合gson直接拿到返回对象)

```
 new AsyncHttpResponseHandler() {
					public void onSuccess(String response) {
						UserInfoResp resp = new Gson().fromJson(response,
								UserInfoResp.class);
						} else {
							// 报错
							progress.CloseProgress();
							Toast.makeText(LoginActicity.this, resp.errMsg,
									Toast.LENGTH_SHORT).show();
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						onFailurePrint(statusCode, headers, responseBody, error);
					}
				});
				
	/**
	 * 请求onFailur时候的错误打印模版
	 */
	public static void onFailurePrint(int statusCode,Header[] headers,
			byte[] responseBody, Throwable error){
		if(error!=null){
			Log.e("ossclient", "statusCode="+statusCode,error);
		}else{
			Log.e("ossclient", "statusCode="+statusCode+" without Exception");
		}
		if (responseBody!=null) {
			try {
				Log.e("ossclient", new String(responseBody, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}		
```

 

4\. 批量图片上传； 如果需要等待全部结果的返回，可以使用 CountDownLatch

http://developer.android.com/reference/java/util/concurrent/CountDownLatch.html

 

原以为安卓里面没有这种java特性，于是自己写了老半天，主要是两个坑：

1.、 计数对象必须加volatile   private volatile int count\_OK = 0;

2、 需单独开线程来循环计数，如果主线程做循环计数，while会导致无法处理response。

 

```
			//等待全部上传ok再提交后台
			new Thread(){public void run(){
				while(count_OK < size_ALL){
					try {
						sleep(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.println("haha");
				addPics();	
			}}.start();	
```