标签:
public class VolleyTimeOutTestDemo extends Request<String> { Listener<String> mListener; public VolleyTimeOutTestDemo(int method, String url, Listener<String> mListener, ErrorListener listener) { super(method, url, listener); this.mListener = mListener; } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { // 执行耗时操作 SystemClock.sleep(10000); System.out.println("当前线程是:" + Thread.currentThread()); return Response.success(new String(response.data), HttpHeaderParser.parseCacheHeaders(response)); } @Override protected void deliverResponse(String response) { mListener.onResponse(response); } }
这是自定义的Request,执行耗时操作是在线程中
Request request = new VolleyTimeOutTestDemo(Method.GET, "http://www.baidu.com", new Listener<String>() { @Override public void onResponse(final String response) { System.out.println("volley耗时十秒返回当前线程是:" + Thread.currentThread()); System.out.println("volley耗时十秒返回结果是:" + response); Toast.makeText(getApplicationContext(), "volley在主线程中返回", 1).show(); // new Thread(new Runnable() { // // @Override // public void run() { // // SystemClock.sleep(10000);// 睡眠10s // // System.out.println("volley耗时十秒返回结果是:" + response); // runOnUiThread(new Runnable() { // // @Override // public void run() { // Toast.makeText(getApplicationContext(), "volley在主线程中返回", // 1).show(); // // } // }); // // } // }).start(); } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { System.err.print("volley返回error是:" + error); } });
所以在response中不能执行耗时的操作,否则会阻塞线程。而在自定义的Response中执行耗时操作,不会阻塞主线程的执行。
同时注意:1.线程暂停用SystemColor.sleep();而不能用Thread.sleep();(不起作用);
2.两种方式进行阻塞操作,注意注释的地方
标签:
原文地址:http://blog.csdn.net/telenewbie/article/details/45689453