Cancel current connection when user clicks

I searched about this, but I did not find my specific question. I understand that AskyncTask can be undone with .cancel(true) , but this will only happen if I have a loop in which I can check the value of isCanceled() .

But my question is here: how can I cancel AsyncTask (which is stuck in httpclient.execute() ) when the user clicks back? If the user goes from this operation and goes to another, I don’t want the uncontrolled number of AsyncTask starts to run, as this can lead to memory problems, the user can move back and forth and create an undefined number of tasks. That's why I want to close them. Does anyone know the way? I am posting the code that I use to connect:

 public class Test extends Activity { @Override protected void onStart() { super.onStart(); new ConnectionTask().execute("https://www.mywebserver.com/webservice.php?param1=test"); } private class ConnectionTask extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... params) { try { HttpClient httpclient = DefaultHttpClient(params,clientConnectionManager); HttpPost httpPost = new HttpPost(params[0]); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if(httpEntity != null) return EntityUtils.toString(httpEntity); } catch (Exception e) { e.printStackTrace(); } return null; } } } 

Do you know what I have to add to onStop () to cancel the current httpClient.execute () function? Sometimes stuck almost forever.

I would really appreciate your help, thanks a lot in advance.

UPDATE

If I close the ConnectionManager , I must again acknowledge for https, right? Look at this code when I create httpClient , I use it for https:

 HttpClient httpclient = DefaultHttpClient(params,clientConnectionManager); 

Thank you all for your prompt answers and the variety of solutions offered here. I will try to use timeouts (in order not to wait too much) + the cancel() function to avoid processing onPostExecute . I will say if results are expected! Thank you very much!

+4
source share
6 answers

There is a cancel() method in the AsyncTask class. Maintaining a member in asynctask and canceling it in onDestroy(). , then set the member to null.

Update

Use the ClientConnectionManager to turn off the connection.

http://developer.android.com/reference/org/apache/http/conn/ClientConnectionManager.html

Update 2

Set this link to set a timeout for your connection.

How to set HttpResponse timeout for Android in Java

+1
source

according to the HttpClient Docs , use HttpUriRequest#abort() to cancel the request

1.4. Cancel requests

In some situations, the HTTP request cannot complete within the expected time interval due to the high load on the target server or too many concurrent requests issued on the client side. In such cases, it may be necessary to prematurely terminate the request and unlock the execution thread blocked in the I / O operation. HTTP requests made by HttpClient can be interrupted at any stage of execution by calling the HttpUriRequest # abort () method. This method is thread safe and can be called from any thread. When an HTTP request is interrupted, its execution flow, even if it is blocked in an I / O operation, is guaranteed to be unlocked by choosing InterruptedIOException

+4
source

My understanding is that httpClient.execute() blocks, so there is no code to check the value of isCancelled() . And you do not want to close the connection manager.

This might be a bit hacky, but instead of some better solutions, what happens if you call Thread.interrupt() on a thread and httpClient.execute() blocked?

A quick test can confirm this, just add a private instance variable of type Thread inside your ConnectionTask definition, set it to Thread.currentThread() at the top of doBackground() and add a public method that calls .interrupt() on it.

If you're lucky, this will cause httpClient.execute() to exit immediately, throwing an exception. You can catch this and do whatever you need before the method call ends and AsyncTask ends naturally.

+1
source

You can override

onPause() an activity method and write a break code there. If this parameter is defined for the back button, you can override

onBackButtonPressed() to stop execution.

0
source

In onPause() or onBackButtonPressed() call cancel() in your task. In doInBackground() right after

 HttpResponse httpResponse = httpClient.execute(httpPost); 

Check isCanceled() and return immediately if true.

Of course, you still have the risk of running several tasks, but since this operation is controlled by the user interface (this is a task launched by user interactions), there should be no more than two of them at the same time, provided that the timeout on HttpClient is reasonable.


Update

You can also disable the connection manager as soon as you determine that the task should be canceled. view documents

This should close the sockets and cause an immediate return from execute() . Connection Manager is installed when creating DefaultHttpClient .

0
source

Well, there is a quick fix to this problem that I used in my case. It may not be as if you returned the application, it will immediately respond, but in the background the network will continue to work (until a timeout is set) without blocking the application: -

All network operations in the new service are told by NSERV. Make NSERV an extension of the Thread class and perform all network operations in the run method. For clarity in the code, it is better to activate the activity / service that starts NSERV, also extend the Thread class and start NSERV from their start method.

Then use static fields or singleton to access the variables in the activity / service from NSERV.

EX:

 public class NSERV extends Service implements Runnable{ public int onStartCommand (Intent intent, int flags, int startId) { Thread t = new Thread (this, "abc"); t.start(); return super.onStartCommand(intent, flags, startId); } public void run() { //NETWORK OPERATION... onDestroy(); } public void onDestroy() { stopSelf(); super.onDestroy(); } } 
0
source

All Articles