Search code examples
androidsocketsandroid-asynctask

how to use of Asynctask with sockets


I do have a problem working with my application. I am using AsyncTask class to perform my background operation as working with Sockets. I believe it is good in Background.

Well, in my application, I have a UDP listener and a UDP sender that are listening from and to a server respectively any sort of data, and I have made async classes for both of them. Now I want both the AsyncTask classes to be executed from my main activity on a button click, that I am able to do, and I have a stop button to stop the execution, but once I click on the stop button, the thread still keeps running, the reason is, after calling the onCancelled() of AsyncTask, its calling postexecute() and in my postexecute(), I am making an object of my AsyncTask class and calling execute so that my listener and sender keeps running i.e. doinBackground() always keeps calling itself and listener and sender keeps working.

I know that making an object of Asynctask class in postexecute() is not a good idea because it will be in an infinite loop, but if I am able to cancel the execution on stop button where I am calling oncancelled(), it may work for me.

Please help me with this.


Solution

  • I think that your problem is that when you cancel your asynkTask, you're actually canceling only the outer most asynckTask which was called in the activity but as you've run other instances of your asyncTask recursively, then you've to cancel them all to get the whole thing stopped.

    why don't you remove your code from inside doInBackground() and put it inside a method and call it from inside the doInBackground() as follows:

    protected Void doInBackground(Object... params) {
    while(!isCancelled()){
    //call the method
    }
    return yourReturnType;
    }