Android 异步网络请求及协调CountDownLatch

来源:互联网 发布:马伯庸作品知乎 编辑:程序博客网 时间:2024/05/20 17:10

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();}}@Overridepublic 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 blocke.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 blocke.printStackTrace();}}System.out.println("haha");addPics();}}.start();

 

0 0
原创粉丝点击