android请求网络——第三方库android-async-http的使用(3)

本文系作者原创,转载请附原文地址,谢谢!

原文地址:http://blog.csdn.net/a774057695/article/details/47337547


前言

         之前我们大致了解了如何访问,我想这一篇不急着去做拿到数据之后的处理,而是做取消访问。

         访问网络是一个耗时操作,我们绝对不会将这一操作放在主线程中,我想我们一定会考虑如何礼貌的通知用户当前是等待过程,甚至将这一过程显得有趣、文艺……但不可否认用户有直接离开的可能。也许我们遇到过这些情况:

1.       提示等待的ProgressDialog对象被设置为不可取消,无论你是点返回键,点背景都不被响应,最终惹恼用户。

2.       提示等待的ProgressDialog对象可以取消且用户来到了其他界面,原先的界面多半是没有被销毁而是存在于activity栈的非顶部位置,当网络请求得到结果(哪怕是不如意的结果),该条线程也会执行后续的逻辑而将该activity调回前台,很粗鲁的打断用户。

3.       你考虑到了以上情况,对该线程进行了处理,但是访问网络的请求并没有被真正取消,只是在后台消耗了流量并且没有做任何有价值事情。

        我想还没有很好的解决这些问题的朋友们对自己的代码一定不满意。aah中对这块儿处理的不错。  

        在第一篇中我们也涉及了代码,按照官方的建议,每次用构造函数获取HttpClient实例的时候应当给context。所以有几点说明:

1.       静态方法有context引用会对GC回收有影响,这里是demo,不处理这些问题

2.       不携带参数的post的方法(我怎么都觉得没必要,用不着)的原型需要注意一下

3.   第一篇中就不修改了,

        先整理一下sample中要用到的url,也是从官方例子中抠出来的,我不做web开发,所以一些方便的测试地址也不清楚,真有一种书到用时方恨少的感觉。

方式

方法

baseurl

get

getWithoutParams

http://httpbin.org/delay/6

getWithparams

http://httpbin.org/delay/6

post

postWithParams

https://httpbin.org/post

 目的说明

本篇主要是演示取消请求功能,取消有三种主要方式:
  1. 全部取消
  2. 按照tag取消
  3. 取消request handle
其实还有一个主要方法,需要context,将引用该context的requests全部cancel掉,本篇中就不演示了,(其实将本系列的前三篇看完,对aah项目已经有一定的了解了,可以去看项目源码了,不像才拿到手的时候直接去看源码那样烦躁)。

限于经验,我对测试的规范不是很了解,话说回来这篇也只是尝试去用一些功能,利用log去印证。
这次我们会做这些事情:
  1. 发起一个请求看效果
  2. 发起多个相同的请求看效果
  3. 发起多个不同方式的请求看效果
  4. 发起一个请求在得到返回前让程序处于非最前看效果
  5. 发起多个请求在得到返回前让程序处于非最前看效果
  6. 发起一个请求在得到返回前使用三种方式取消看效果
  7. 发起多个请求在得到返回前使用三种方式取消看效果

代码

一共三个代码文件:布局文件,HttpUtil方法类和activity实例。
  • 新建项目的注意internet权限
  • 为了方便操作,我在请求时都没有显示dialog之类的操作。
  • 和第一篇不同的是使用到的都提供了context
  • 作为sample的代码质量很低,不要照搬到应用,目的在于了解aah
  • 注意!注意!注意!为了方便操作,http://httpbin.org/delay/6是延迟6秒响应的,你可以将其调小一点,也可以调大一点,但是连接超时设置时间请设置的合理一点。
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <Button
                android:id="@+id/btn_getWithoutParams"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="getWithoutParams" />

            <Button
                android:id="@+id/btn_getWithParams"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="getWithParams" />

            <Button
                android:id="@+id/btn_postWithParams"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="postWithParams" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <Button
                    android:id="@+id/btn_addHandle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="SaveHandle" />

                <Button
                    android:id="@+id/btn_cancelHandle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="10dp"
                    android:text="cancel request handle" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <Button
                    android:id="@+id/btn_setTag"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="requestWithTag" />

                <Button
                    android:id="@+id/btn_cancelTag"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="cancel by tag" />

              
            </LinearLayout>

            <Button
                android:id="@+id/btn_cancelAll"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="cancel all" />

        </LinearLayout>
    </ScrollView>

</LinearLayout>

它看起来会是这样:

(我总算发现怎么调大小了,丑了点,别介意)

HttpUtil.java

package [your package name]

import java.util.LinkedList;
import java.util.List;

import android.content.Context;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;

public class HttpUtil {
	//实例化对象
    private static AsyncHttpClient client =new AsyncHttpClient();
    private static List<RequestHandle> requestHandles = new LinkedList<RequestHandle>();
    
    //设置链接超时,如果不设置,默认为10s
    static
    {
        client.setTimeout(10000);
    }
    
    /**
     * 不带访问params,get方式
     * 返回byte[],可自行处理
     * */
    public static void getWithoutParams(Context mContext, String urlString,AsyncHttpResponseHandler res)
    {
        client.get(mContext ,urlString, res);
    }
    
    /**
     * 带访问params,get方式
     * 返回byte[],可自行处理
     * */
    public static void getWithParams(Context mContext , String urlString,RequestParams params,AsyncHttpResponseHandler res)
    {
        client.get(mContext, urlString, params,res);
    }
    
    /**
     * 不带params、get方法
     * 获取JsonObject或者JsonArray
     * 好像没用
     * */
    public static void getWithoutParamsForJson(Context mContext , String urlString,JsonHttpResponseHandler res)
    {
        client.get(mContext ,urlString, res);
    }
    
    /**
     * 带params、get方法
     * 获取JsonObject或者JsonArray
     * 好像没用
     * */
    public static void getWithParamsForJson(Context mContext, String urlString,RequestParams params,JsonHttpResponseHandler res)
    {
        client.get(mContext,urlString, params,res);
    }
    
    /**
     * 下载数据使用
     * 返回byte数据
     * */
    public static void get(String uString, BinaryHttpResponseHandler bHandler)
    {
        client.get(uString, bHandler);
    }
    
    /**
     * 不带访问params, post
     * 这种情况很少见,一般都是传params的
     * */
    public static void postWithoutParams(String urlString, AsyncHttpResponseHandler res)
    {
    	client.post(urlString, res);
    }
    
    /**
     * 带访问params,post
     * */
    public static void postWithParams(Context mContext, String urlString,RequestParams params, AsyncHttpResponseHandler res)
    {
    	client.post(mContext, urlString, params, res);
    }
    
    
    public static AsyncHttpClient getClient()
    {
        return client;
    }
    
    
    public static void setTag(Context mContext,String urlString,AsyncHttpResponseHandler res,int tag)
    {
    	client.get(mContext, urlString, res).setTag(tag);
    }
    
    /**
     * 添加handle
     * */
    public static void setHandle(Context mContext,String urlString,AsyncHttpResponseHandler res)
    {
    	addHandle(getWithoutParams2(mContext,urlString,res));
    }
    
    //将handle添加到关系链表
    private static void addHandle(RequestHandle handle) {
		if(null!=handle) {
			requestHandles.add(handle);
		}
	}
    
    //返回记录handle的关系列表
    public static List<RequestHandle> getRequestHandles() {
        return requestHandles;
    }

    //get方式,返回RequestHandle
    private static RequestHandle getWithoutParams2(Context mContext, String urlString,AsyncHttpResponseHandler res)
    {
       return client.get(mContext ,urlString, res);
    }
}
MainActivity.java

package [your package name]

import org.apache.http.Header;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;

@SuppressWarnings("deprecation")
public class MainActivity extends Activity {
	private Context mContext = this;
	
	private int tag = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button getWithParams = (Button)findViewById(R.id.btn_getWithParams);
		Button getWithoutParams = (Button)findViewById(R.id.btn_getWithoutParams);
		Button postWithParams = (Button)findViewById(R.id.btn_postWithParams);
		Button cancelHandle = (Button)findViewById(R.id.btn_cancelHandle);
		Button cancelTag = (Button)findViewById(R.id.btn_cancelTag);
		Button cancelAll = (Button)findViewById(R.id.btn_cancelAll);
		Button requestSaveHandle = (Button)findViewById(R.id.btn_addHandle);
		Button requestWithTag = (Button)findViewById(R.id.btn_setTag);
		
		getWithoutParams.setOnClickListener(bt_listener);
		getWithParams.setOnClickListener(bt_listener);
		postWithParams.setOnClickListener(bt_listener);
		cancelAll.setOnClickListener(bt_listener);
		cancelHandle.setOnClickListener(bt_listener);
		cancelTag.setOnClickListener(bt_listener);
		requestSaveHandle.setOnClickListener(bt_listener);
		requestWithTag.setOnClickListener(bt_listener);
	}
	OnClickListener bt_listener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch(v.getId()) {
				case R.id.btn_getWithoutParams:
					getWithoutParams();
					break;
				case R.id.btn_getWithParams:
					getWithParams();
					break;
				case R.id.btn_postWithParams:
					postWithParams();
					break;
				case R.id.btn_addHandle:
					addHandle();
					break;
				case R.id.btn_cancelHandle:
					cancelHandle();
					break;
				case R.id.btn_setTag:
					setTag();
					break;
				case R.id.btn_cancelTag:
					cancelByTag();
					break;
				case R.id.btn_cancelAll:
					cancelall();
					break;
				default:
					break;
			}
		}
	};
	
	
	 private void getWithoutParams() {
	        String urlString = "http://httpbin.org/delay/6";
	        HttpUtil.getWithoutParams(mContext,urlString, new AsyncHttpResponseHandler() {

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					Log.i("statuscode:", ""+arg0);
					arg3.printStackTrace(System.out);
				}
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					Log.i("statuscode:", ""+arg0);
					String jsonString = new String(arg2);
					Log.i("response:",jsonString);
				}
	        });
	    }
	
	 
	 protected void addHandle() {
		 String urlString = "http://httpbin.org/delay/6";
	        HttpUtil.setHandle(mContext,urlString, new AsyncHttpResponseHandler() {

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					Log.i("statuscode:", ""+arg0);
					arg3.printStackTrace(System.out);
				}
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					Log.i("statuscode:", ""+arg0);
					String jsonString = new String(arg2);
					Log.i("response:",jsonString);
				}
	        });
		
	}


	protected void cancelHandle() {

		 Log.d("CancelLog", String.format("Number of handles found: %d", HttpUtil.getRequestHandles().size()));
	        int counter = 0;
	        for (RequestHandle handle : HttpUtil.getRequestHandles()) {
	            if (!handle.isCancelled() && !handle.isFinished()) {
	                Log.d("CancelLog", String.format("Cancelling handle %d", counter));
	                Log.d("CancelLog", String.format("Handle %d cancel", counter) + (handle.cancel(true) ? " succeeded" : " failed"));
	            } else {
	                Log.d("CancelLog", String.format("Handle %d already non-cancellable", counter));
	            }
	            counter++;
	        }
	}


	protected void setTag() {
		 String urlString = "http://httpbin.org/delay/6";
	        HttpUtil.setTag(mContext,urlString, new AsyncHttpResponseHandler() {

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					Log.i("statuscode:", ""+arg0);
					arg3.printStackTrace(System.out);
				}
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					Log.i("statuscode:", ""+arg0);
					String jsonString = new String(arg2);
					Log.i("response:",jsonString);
				}
	        },tag);
	}


	private void getWithParams() {
	        String urlString = "http://httpbin.org/delay/6";
	        RequestParams params = new RequestParams();
	        params.add("key1", "v1");
	        params.add("key2", "v2");
	        
	        HttpUtil.getWithParams(mContext, urlString, params, new AsyncHttpResponseHandler() {

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					Log.i("statuscode:", ""+arg0);
					arg3.printStackTrace(System.out);
				}
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					Log.i("statuscode:", ""+arg0);
					String jsonString = new String(arg2);
					Log.i("response:",jsonString);
				}
	        });
	    }
	 
	 
	 private void cancelall() {
		 HttpUtil.getClient().cancelAllRequests(true);
	 }

	 private void cancelByTag() {
		 HttpUtil.getClient().cancelRequestsByTAG(tag, true);
	 }
	 
	private void postWithParams() {
        String urlString = "https://httpbin.org/post";
        RequestParams params = new RequestParams();
        params.add("postParam1", "p1");
        params.add("postParam2", "p2");

        
        HttpUtil.postWithParams(mContext,urlString, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				Log.i("statuscode:", ""+arg0);
				String er = new String(arg2);
				Log.i("errorResponse:",""+er);
				arg3.printStackTrace(System.out);
			}
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				Log.i("statuscode:", ""+arg0);
				String jsonString = new String(arg2);
				Log.i("response:",jsonString);
			}
        });
	}

}

测试内容

我们先发起一个请求,然后看log输出,会是这样:
08-07 13:44:07.453: I/View(14827): Touch down dispatch to android.widget.Button{42a2e598 VFED..C. ........ 0,0-656,97 #7f080002 app:id/btn_getWithoutParams}, event = MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=157.73648, y[0]=43.82669, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=487004872, downTime=487004872, deviceId=3, source=0x1002 }
08-07 13:44:07.517: I/View(14827): Touch up dispatch to android.widget.Button{42a2e598 VFED..C. ...p.... 0,0-656,97 #7f080002 app:id/btn_getWithoutParams}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=156.73787, y[0]=38.830597, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=487004938, downTime=487004872, deviceId=3, source=0x1002 }
08-07 13:44:07.528: V/SettingsProviderInterface(14827):  from settings cache , name = sound_effects_enabled , value = 0
08-07 13:44:07.528: D/dalvikvm(14827): create interp thread : stack size=128KB
08-07 13:44:07.528: D/dalvikvm(14827): create new thread
08-07 13:44:07.529: D/dalvikvm(14827): new thread created
08-07 13:44:07.529: D/dalvikvm(14827): update thread list
08-07 13:44:07.529: D/dalvikvm(14827): threadid=12: interp stack at 0x60d80000
08-07 13:44:07.529: D/dalvikvm(14827): init ref table
08-07 13:44:07.529: D/dalvikvm(14827): init mutex
08-07 13:44:07.529: D/dalvikvm(14827): threadid=12: created from interp
08-07 13:44:07.529: D/dalvikvm(14827): start new thread
08-07 13:44:07.529: D/dalvikvm(14827): threadid=12: notify debugger
08-07 13:44:07.529: D/dalvikvm(14827): threadid=12 (pool-1-thread-6): calling run()
08-07 13:44:07.530: I/System.out(14827): [CDS]rx timeout:1
08-07 13:44:07.530: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:44:07.530: I/System.out(14827): [CDS]close[53132]
08-07 13:44:07.530: I/System.out(14827): close [socket][/0.0.0.0:53132]
08-07 13:44:07.532: D/libc-netbsd(14827): getaddrinfo: httpbin.org get result from proxy >>
08-07 13:44:07.532: I/System.out(14827): propertyValue:true
08-07 13:44:07.533: I/System.out(14827): [socket][5] connection /54.175.219.8:80;LocalPort=38166(10000)
08-07 13:44:07.533: I/System.out(14827): [CDS]connect[/54.175.219.8:80] tm:10
08-07 13:44:07.534: D/Posix(14827): [Posix_connect Debug]Process com.example.testasynchttp :80 
08-07 13:44:07.775: I/System.out(14827): [socket][/192.168.255.220:38166] connected
08-07 13:44:07.775: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:44:07.775: I/System.out(14827): [CDS]SO_SND_TIMEOUT:0
08-07 13:44:07.776: I/System.out(14827): >doSendRequest
08-07 13:44:07.776: I/System.out(14827): <doSendRequest
08-07 13:44:14.022: V/AsyncHttpRH(14827): Progress 241 from 241 (100%)
<span style="background-color: rgb(204, 204, 204);">08-07 13:44:14.022: I/statuscode:(14827): 200
08-07 13:44:14.022: I/response:(14827): {
08-07 13:44:14.022: I/response:(14827):   "args": {}, 
08-07 13:44:14.022: I/response:(14827):   "data": "", 
08-07 13:44:14.022: I/response:(14827):   "files": {}, 
08-07 13:44:14.022: I/response:(14827):   "form": {}, 
08-07 13:44:14.022: I/response:(14827):   "headers": {
08-07 13:44:14.022: I/response:(14827):     "Accept-Encoding": "gzip", 
08-07 13:44:14.022: I/response:(14827):     "Content-Length": "0", 
08-07 13:44:14.022: I/response:(14827):     "Host": "httpbin.org"
08-07 13:44:14.022: I/response:(14827):   }, 
08-07 13:44:14.022: I/response:(14827):   "origin": "222.92.185.206", 
08-07 13:44:14.022: I/response:(14827):   "url": "http://httpbin.org/delay/6"
08-07 13:44:14.022: I/response:(14827): }</span>
08-07 13:45:14.022: D/dalvikvm(14827): threadid=12: exiting
08-07 13:45:14.022: D/dalvikvm(14827): threadid=12: bye!
你可以多尝试几个,放松一下。

然后发起多个请求,多点几下就好了。我连续点击三次getWithParams,可以看到最后的三次输出:
08-07 13:48:42.202: V/SettingsProviderInterface(14827):  from settings cache , name = sound_effects_enabled , value = 0
08-07 13:48:42.204: D/dalvikvm(14827): create interp thread : stack size=128KB
08-07 13:48:42.204: D/dalvikvm(14827): create new thread
08-07 13:48:42.204: D/dalvikvm(14827): new thread created
08-07 13:48:42.204: D/dalvikvm(14827): update thread list
08-07 13:48:42.205: D/dalvikvm(14827): threadid=12: interp stack at 0x60d80000
08-07 13:48:42.205: D/dalvikvm(14827): init ref table
08-07 13:48:42.205: D/dalvikvm(14827): init mutex
08-07 13:48:42.205: D/dalvikvm(14827): threadid=12: created from interp
08-07 13:48:42.205: D/dalvikvm(14827): start new thread
08-07 13:48:42.206: D/dalvikvm(14827): threadid=12: notify debugger
08-07 13:48:42.206: D/dalvikvm(14827): threadid=12 (pool-1-thread-7): calling run()
08-07 13:48:42.207: I/System.out(14827): [CDS]rx timeout:1
08-07 13:48:42.207: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:48:42.208: I/System.out(14827): [CDS]close[38166]
08-07 13:48:42.208: I/System.out(14827): close [socket][/0.0.0.0:38166]
08-07 13:48:42.210: D/libc-netbsd(14827): getaddrinfo: httpbin.org get result from proxy >>
08-07 13:48:42.210: I/System.out(14827): propertyValue:true
08-07 13:48:42.214: I/System.out(14827): [socket][6] connection /54.175.219.8:80;LocalPort=49560(10000)
08-07 13:48:42.214: I/System.out(14827): [CDS]connect[/54.175.219.8:80] tm:10
08-07 13:48:42.215: D/Posix(14827): [Posix_connect Debug]Process com.example.testasynchttp :80 
08-07 13:48:42.250: I/View(14827): Touch up dispatch to android.widget.Button{42a2f000 VFED..C. ...p..ID 0,97-656,194 #7f080003 app:id/btn_getWithParams}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=487.2788, y[0]=45.74942, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=487279671, downTime=487279590, deviceId=3, source=0x1002 }
08-07 13:48:42.255: V/SettingsProviderInterface(14827):  from settings cache , name = sound_effects_enabled , value = 0
08-07 13:48:42.257: D/dalvikvm(14827): create interp thread : stack size=128KB
08-07 13:48:42.257: D/dalvikvm(14827): create new thread
08-07 13:48:42.257: D/dalvikvm(14827): new thread created
08-07 13:48:42.257: D/dalvikvm(14827): update thread list
08-07 13:48:42.257: D/dalvikvm(14827): threadid=13: interp stack at 0x60da2000
08-07 13:48:42.257: D/dalvikvm(14827): init ref table
08-07 13:48:42.257: D/dalvikvm(14827): init mutex
08-07 13:48:42.257: D/dalvikvm(14827): threadid=13: created from interp
08-07 13:48:42.257: D/dalvikvm(14827): start new thread
08-07 13:48:42.257: D/dalvikvm(14827): threadid=13: notify debugger
08-07 13:48:42.257: D/dalvikvm(14827): threadid=13 (pool-1-thread-8): calling run()
08-07 13:48:42.259: I/System.out(14827): [CDS]rx timeout:1
08-07 13:48:42.259: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:48:42.259: I/System.out(14827): [CDS]close[53062]
08-07 13:48:42.260: I/System.out(14827): close [socket][/0.0.0.0:53062]
08-07 13:48:42.261: I/System.out(14827): [socket][7] connection /54.175.219.8:80;LocalPort=33638(10000)
08-07 13:48:42.261: I/System.out(14827): [CDS]connect[/54.175.219.8:80] tm:10
08-07 13:48:42.261: D/Posix(14827): [Posix_connect Debug]Process com.example.testasynchttp :80 
08-07 13:48:42.327: I/View(14827): Touch down dispatch to android.widget.Button{42a2f000 VFED..C. ......ID 0,97-656,194 #7f080003 app:id/btn_getWithParams}, event = MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=483.28436, y[0]=44.750183, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=487279735, downTime=487279735, deviceId=3, source=0x1002 }
08-07 13:48:42.411: I/View(14827): Touch up dispatch to android.widget.Button{42a2f000 VFED..C. ...p.... 0,97-656,194 #7f080003 app:id/btn_getWithParams}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=483.28436, y[0]=44.750183, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=487279829, downTime=487279735, deviceId=3, source=0x1002 }
08-07 13:48:42.424: V/SettingsProviderInterface(14827):  from settings cache , name = sound_effects_enabled , value = 0
08-07 13:48:42.428: D/dalvikvm(14827): create interp thread : stack size=128KB
08-07 13:48:42.428: D/dalvikvm(14827): create new thread
08-07 13:48:42.428: D/dalvikvm(14827): new thread created
08-07 13:48:42.428: D/dalvikvm(14827): update thread list
08-07 13:48:42.428: D/dalvikvm(14827): threadid=14: interp stack at 0x60dc4000
08-07 13:48:42.429: D/dalvikvm(14827): init ref table
08-07 13:48:42.429: D/dalvikvm(14827): init mutex
08-07 13:48:42.429: D/dalvikvm(14827): threadid=14: created from interp
08-07 13:48:42.429: D/dalvikvm(14827): start new thread
08-07 13:48:42.429: D/dalvikvm(14827): threadid=14: notify debugger
08-07 13:48:42.429: D/dalvikvm(14827): threadid=14 (pool-1-thread-9): calling run()
08-07 13:48:42.433: I/System.out(14827): [CDS]rx timeout:1
08-07 13:48:42.433: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:48:42.434: I/System.out(14827): [CDS]close[44353]
08-07 13:48:42.435: I/System.out(14827): close [socket][/0.0.0.0:44353]
08-07 13:48:42.438: I/System.out(14827): [socket][8] connection /54.175.219.8:80;LocalPort=44408(10000)
08-07 13:48:42.438: I/System.out(14827): [CDS]connect[/54.175.219.8:80] tm:10
08-07 13:48:42.439: D/Posix(14827): [Posix_connect Debug]Process com.example.testasynchttp :80 
08-07 13:48:42.581: I/System.out(14827): [socket][/192.168.255.220:49560] connected
08-07 13:48:42.581: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:48:42.581: I/System.out(14827): [CDS]SO_SND_TIMEOUT:0
08-07 13:48:42.586: I/System.out(14827): >doSendRequest
08-07 13:48:42.589: I/System.out(14827): <doSendRequest
08-07 13:48:43.603: I/System.out(14827): [socket][/192.168.255.220:33638] connected
08-07 13:48:43.604: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:48:43.604: I/System.out(14827): [CDS]SO_SND_TIMEOUT:0
08-07 13:48:43.607: I/System.out(14827): >doSendRequest
08-07 13:48:43.608: I/System.out(14827): <doSendRequest
08-07 13:48:43.783: I/System.out(14827): [socket][/192.168.255.220:44408] connected
08-07 13:48:43.783: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:48:43.783: I/System.out(14827): [CDS]SO_SND_TIMEOUT:0
08-07 13:48:43.786: I/System.out(14827): >doSendRequest
08-07 13:48:43.787: I/System.out(14827): <doSendRequest
08-07 13:48:48.936: V/AsyncHttpRH(14827): Progress 296 from 296 (100%)
<span style="background-color: rgb(204, 204, 204);">08-07 13:48:48.937: I/statuscode:(14827): 200
08-07 13:48:48.939: I/response:(14827): {
08-07 13:48:48.939: I/response:(14827):   "args": {
08-07 13:48:48.939: I/response:(14827):     "key1": "v1", 
08-07 13:48:48.939: I/response:(14827):     "key2": "v2"
08-07 13:48:48.939: I/response:(14827):   }, 
08-07 13:48:48.939: I/response:(14827):   "data": "", 
08-07 13:48:48.939: I/response:(14827):   "files": {}, 
08-07 13:48:48.939: I/response:(14827):   "form": {}, 
08-07 13:48:48.939: I/response:(14827):   "headers": {
08-07 13:48:48.939: I/response:(14827):     "Accept-Encoding": "gzip", 
08-07 13:48:48.939: I/response:(14827):     "Content-Length": "0", 
08-07 13:48:48.939: I/response:(14827):     "Host": "httpbin.org"
08-07 13:48:48.939: I/response:(14827):   }, 
08-07 13:48:48.939: I/response:(14827):   "origin": "222.92.185.206", 
08-07 13:48:48.939: I/response:(14827):   "url": "http://httpbin.org/delay/6?key1=v1&key2=v2"
08-07 13:48:48.939: I/response:(14827): }
08-07 13:48:50.678: V/AsyncHttpRH(14827): Progress 296 from 296 (100%)
08-07 13:48:50.680: I/statuscode:(14827): 200
08-07 13:48:50.681: I/response:(14827): {
08-07 13:48:50.681: I/response:(14827):   "args": {
08-07 13:48:50.681: I/response:(14827):     "key1": "v1", 
08-07 13:48:50.681: I/response:(14827):     "key2": "v2"
08-07 13:48:50.681: I/response:(14827):   }, 
08-07 13:48:50.681: I/response:(14827):   "data": "", 
08-07 13:48:50.681: I/response:(14827):   "files": {}, 
08-07 13:48:50.681: I/response:(14827):   "form": {}, 
08-07 13:48:50.681: I/response:(14827):   "headers": {
08-07 13:48:50.681: I/response:(14827):     "Accept-Encoding": "gzip", 
08-07 13:48:50.681: I/response:(14827):     "Content-Length": "0", 
08-07 13:48:50.681: I/response:(14827):     "Host": "httpbin.org"
08-07 13:48:50.681: I/response:(14827):   }, 
08-07 13:48:50.681: I/response:(14827):   "origin": "222.92.185.206", 
08-07 13:48:50.681: I/response:(14827):   "url": "http://httpbin.org/delay/6?key1=v1&key2=v2"
08-07 13:48:50.681: I/response:(14827): }
08-07 13:48:50.854: V/AsyncHttpRH(14827): Progress 296 from 296 (100%)
08-07 13:48:50.854: I/statuscode:(14827): 200
08-07 13:48:50.855: I/response:(14827): {
08-07 13:48:50.855: I/response:(14827):   "args": {
08-07 13:48:50.855: I/response:(14827):     "key1": "v1", 
08-07 13:48:50.855: I/response:(14827):     "key2": "v2"
08-07 13:48:50.855: I/response:(14827):   }, 
08-07 13:48:50.855: I/response:(14827):   "data": "", 
08-07 13:48:50.855: I/response:(14827):   "files": {}, 
08-07 13:48:50.855: I/response:(14827):   "form": {}, 
08-07 13:48:50.855: I/response:(14827):   "headers": {
08-07 13:48:50.855: I/response:(14827):     "Accept-Encoding": "gzip", 
08-07 13:48:50.855: I/response:(14827):     "Content-Length": "0", 
08-07 13:48:50.855: I/response:(14827):     "Host": "httpbin.org"
08-07 13:48:50.855: I/response:(14827):   }, 
08-07 13:48:50.855: I/response:(14827):   "origin": "222.92.185.206", 
08-07 13:48:50.855: I/response:(14827):   "url": "http://httpbin.org/delay/6?key1=v1&key2=v2"
08-07 13:48:50.855: I/response:(14827): }</span>

你可以在多戳一戳,戳点不同的

接下来做一个有意思的事情,发起get请求(你一定会想为什么不用post,别想多,只是这里get方式请求的网址响应时间长,你来得及反应而已),点一下,然后将程序处于非前台(back或者home都行)
log就不贴了,你会发现log还是输出了得到的内容,这就是我们要研究cancel的原因,毕竟我们很少会去做退出一个activity就将其从栈中移除的事情。

现在发起一个请求,然后cancelall,你会发现这样的log:
08-07 13:59:52.360: I/View(14827): Touch down dispatch to android.widget.Button{42b54520 VFED..C. ........ 0,0-656,97 #7f080002 app:id/btn_getWithoutParams}, event = MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=178.70735, y[0]=50.821228, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=487949780, downTime=487949780, deviceId=3, source=0x1002 }
08-07 13:59:52.437: I/View(14827): Touch up dispatch to android.widget.Button{42b54520 VFED..C. ...p.... 0,0-656,97 #7f080002 app:id/btn_getWithoutParams}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=181.7032, y[0]=45.825134, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=487949859, downTime=487949780, deviceId=3, source=0x1002 }
08-07 13:59:52.453: V/SettingsProviderInterface(14827):  from settings cache , name = sound_effects_enabled , value = 0
08-07 13:59:52.453: D/dalvikvm(14827): create interp thread : stack size=128KB
08-07 13:59:52.453: D/dalvikvm(14827): create new thread
08-07 13:59:52.453: D/dalvikvm(14827): new thread created
08-07 13:59:52.453: D/dalvikvm(14827): update thread list
08-07 13:59:52.454: D/dalvikvm(14827): threadid=12: interp stack at 0x60d90000
08-07 13:59:52.454: D/dalvikvm(14827): init ref table
08-07 13:59:52.454: D/dalvikvm(14827): init mutex
08-07 13:59:52.454: D/dalvikvm(14827): threadid=12: created from interp
08-07 13:59:52.454: D/dalvikvm(14827): start new thread
08-07 13:59:52.454: D/dalvikvm(14827): threadid=12: notify debugger
08-07 13:59:52.454: D/dalvikvm(14827): threadid=12 (pool-1-thread-13): calling run()
08-07 13:59:52.455: I/System.out(14827): [CDS]rx timeout:1
08-07 13:59:52.455: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:59:52.455: I/System.out(14827): [CDS]close[60276]
08-07 13:59:52.455: I/System.out(14827): close [socket][/0.0.0.0:60276]
08-07 13:59:52.471: D/libc-netbsd(14827): getaddrinfo: httpbin.org get result from proxy >>
08-07 13:59:52.472: I/System.out(14827): propertyValue:true
08-07 13:59:52.473: I/System.out(14827): [socket][12] connection /54.175.222.246:80;LocalPort=56247(10000)
08-07 13:59:52.473: I/System.out(14827): [CDS]connect[/54.175.222.246:80] tm:10
08-07 13:59:52.474: D/Posix(14827): [Posix_connect Debug]Process com.example.testasynchttp :80 
08-07 13:59:52.819: I/System.out(14827): [socket][/192.168.255.220:56247] connected
08-07 13:59:52.819: I/System.out(14827): [CDS]rx timeout:10000
08-07 13:59:52.819: I/System.out(14827): [CDS]SO_SND_TIMEOUT:0
08-07 13:59:52.820: I/System.out(14827): >doSendRequest
08-07 13:59:52.821: I/System.out(14827): <doSendRequest
08-07 13:59:53.411: I/View(14827): Touch down dispatch to android.widget.Button{42b59410 VFED..C. ........ 0,540-656,636 #7f080009 app:id/btn_cancelAll}, event = MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=307.52844, y[0]=74.38092, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=487950831, downTime=487950831, deviceId=3, source=0x1002 }
08-07 13:59:53.476: I/View(14827): Touch up dispatch to android.widget.Button{42b59410 VFED..C. ...p.... 0,540-656,636 #7f080009 app:id/btn_cancelAll}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=305.53122, y[0]=68.38562, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=487950897, downTime=487950831, deviceId=3, source=0x1002 }
08-07 13:59:53.483: V/SettingsProviderInterface(14827):  from settings cache , name = sound_effects_enabled , value = 0
08-07 13:59:53.483: D/dalvikvm(14827): create interp thread : stack size=128KB
08-07 13:59:53.484: D/dalvikvm(14827): create new thread
08-07 13:59:53.484: D/dalvikvm(14827): new thread created
08-07 13:59:53.484: D/dalvikvm(14827): update thread list
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13: interp stack at 0x60db0000
08-07 13:59:53.484: D/dalvikvm(14827): init ref table
08-07 13:59:53.484: D/dalvikvm(14827): init mutex
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13: created from interp
08-07 13:59:53.484: D/dalvikvm(14827): start new thread
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13: notify debugger
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13 (Thread-5505): calling run()
08-07 13:59:53.484: D/dalvikvm(14827): create interp thread : stack size=128KB
08-07 13:59:53.484: D/dalvikvm(14827): create new thread
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13: exiting
08-07 13:59:53.484: D/dalvikvm(14827): new thread created
08-07 13:59:53.484: D/dalvikvm(14827): update thread list
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13: bye!
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13: interp stack at 0x60dd2000
08-07 13:59:53.484: D/dalvikvm(14827): init ref table
08-07 13:59:53.484: D/dalvikvm(14827): init mutex
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13: created from interp
08-07 13:59:53.484: D/dalvikvm(14827): start new thread
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13: notify debugger
08-07 13:59:53.484: D/dalvikvm(14827): threadid=13 (Thread-5506): calling run()
08-07 13:59:53.485: I/System.out(14827): [CDS]close[56247]
08-07 13:59:53.485: I/System.out(14827): ex:java.net.SocketException: Socket closed
08-07 13:59:53.485: I/System.out(14827): close [socket][/0.0.0.0:56247]
08-07 13:59:53.485: I/System.out(14827): close [socket][/0.0.0.0:56247]
08-07 13:59:53.485: D/dalvikvm(14827): threadid=13: exiting
08-07 13:59:53.485: D/dalvikvm(14827): threadid=13: bye!
08-07 13:59:53.485: V/AsyncHttpRH(14827): Request got cancelled
08-07 13:59:54.987: D/libc-netbsd(14827): getaddrinfo: httpbin.org get result from proxy >>
08-07 13:59:54.987: I/System.out(14827): propertyValue:true
08-07 13:59:54.987: I/System.out(14827): close [socket][/0.0.0.0:-1]
你可以发现连接断开,请求取消了,多发起几个请求看看

好,再点击saveHandle,cancelrequesthandle看看,

再试试tag,这里我没有刷新tag。

后记

这篇冗长的博客也要写完了,大家应该对请求的取消有了一定的了解,也一定有了在某些场景下,在代码中进行请求取消的意识。下一篇不出意外会是得到数据后的处理。




本文系作者原创,转载请附原文地址,谢谢!

原文地址:http://blog.csdn.net/a774057695/article/details/47337547







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值