Search code examples
androidrequestandroidhttpclientandroid-async-http

FileAsyncHttpResponseHandler cancel request


I want to cancel a FileAsyncHttpResponseHandler request in android app, but just one (not all of them). There are these methods available, but none of them cancel the request. It proceeds until the file is completely downloaded.

FileAsyncHttpResponseHandler fileAsyncHttpResponseHandler;
...get request...
fileAsyncHttpResponseHandler.deleteTargetFile();
fileAsyncHttpResponseHandler.onCancel();
fileAsyncHttpResponseHandler.sendCancelMessage();

Please help me!!


Solution

  • I'm dev of said library, and you have basically three options.

    First, obtain RequestHandle from creating request, and cancel through that

    AsyncHttpClient ahc = new AsyncHttpClient();
    RequestHandle rh = ahc.get(context, url, fileResponseHandler);
    rh.cancel();
    

    Second, cancel request by belonging Context

    AsyncHttpClient ahc = new AsyncHttpClient();
    ahc.get(CurrentActivity.this, url, fileResponseHandler);
    ahc.cancelRequests(CurrentActivity.this, boolean mayInterruptIfRunning);
    

    Third, currently in 1.4.8 snapshot (will be released in probably on sunday as 1.4.8 release), put a TAG to request (or implement getTag() in ResponseHandler, and cancel by said TAG)

    String myTag = "my-long-identifier-such-as-uuid";
    AsyncHttpClient ahc = new AsyncHttpClient();
    RequestHandle rh = ahc.get(context, url, fileResponseHandler);
    rh.setTag(myTag);
    ahc.cancelRequestsByTAG(myTag, boolean mayInterruptIfRunning);
    

    or by implementing getTag() from response Handler

    AsyncHttpClient ahc = new AsyncHttpClient();
    ahc.get(context, url, new FileAsyncHttpResponseHandler(){
        // implement all methods
        // override getTag() to identify request associated with this responseHandler
        // for example return "url" for ability to cancel by request URL
        @Override
        public Object getTag() { return url; }
    });
    ahc.cancelRequestsByTAG(url, boolean mayInterruptIfRunning);