Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask android exception (Cannot execute task: the task has already been executed)

I have java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once) although I create a new instance of AsyncTask like this

new ClientEngine(ip, port).execute(WindowsEventsEnum.MouseLeftButtonClick);

Here is my code

    public class ClientEngine extends AsyncTask<WindowsEventsEnum, Void, Void>{
    final String ip;
    final int port;
DatagramSocket socket;
    InetAddress remoteAdress;
    DatagramPacket sendingPacket;
    final String VOLUMEUP = "01";
    final String VOLUMEDOWN = "02";
    final String LMBCLICK = "11";
    final String RMBCLICK = "12";
    final String MMBUP = "21";
    final String MMBDOWN = "22";
    final String ENDCONNECTION = "ec";


    public ClientEngine(String ip, int port) throws SocketException, UnknownHostException {
        this.ip = ip;
        this.port = port;
        socket = new DatagramSocket();
        remoteAdress = InetAddress.getByName(ip);
    }

    public void OpenConnection() throws IOException {


    }

    public void CloseConnection() throws IOException {

socket.close();
    }

    public void MouseLeftButtonClick() throws IOException {
byte[] sendDatagram = LMBCLICK.getBytes();
        sendingPacket = new DatagramPacket(sendDatagram, sendDatagram.length, remoteAdress, port);
        socket.send(sendingPacket);
    }

    public void MouseRightButtonClick() throws IOException {
        byte[] sendDatagram = RMBCLICK.getBytes();
        sendingPacket = new DatagramPacket(sendDatagram, sendDatagram.length, remoteAdress, port);
        socket.send(sendingPacket);
    }

    public void SystemVolumeUp() throws IOException {

    }

    public void SystemVolumeDown() throws IOException {

    }

    @Override
    protected Void doInBackground(WindowsEventsEnum... params) {
        switch (params[0]) {
            case MouseLeftButtonClick:
                try {
                    MouseLeftButtonClick();
                    CloseConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case MouseRightButtonClick:
                try {
                    MouseRightButtonClick();
                    CloseConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
       return null;
    }

}
like image 435
Яктенс Тид Avatar asked May 10 '16 20:05

Яктенс Тид


People also ask

Why AsyncTask is deprecated in Android?

This class was deprecated in API level 30.AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

How to use AsyncTask in Android java?

To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask myTask = new MyTask(); myTask. execute(); In the above snippet we've used a sample classname that extends AsyncTask and execute method is used to start the background thread.

How to cancel Async task Android?

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

What happens if we call Execute () more than once in async task?

Limitation Of AsyncTask If you try to execute more than 138 AsyncTasks the app will crash with java. util. concurrent. RejectedExecutionException.


1 Answers

Sorry if you have already fixed the issue. But generally, whenever you get an exception like this,

java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)

Check whether you are following all the below mentioned rules:

  1. AsyncTask can be executed only once (an exception will be thrown if a second execution is attempted.)

    Just like the case where it is illegal to start a thread more than once.

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

So creating a new instance like new asyncTask().execute(); is the only option

  1. onPreExecute(), doInBackground(), onProgressUpdate(),onPostExecute() shouldn't be called manually.

  2. The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.

  3. The task instance must be created on the UI thread.

  4. execute(Params...) must be invoked on the UI thread.

Make sure you have followed all the 5 rules in your code.

Read more: https://developer.android.com/reference/android/os/AsyncTask.html

like image 171
Ganesh Ramachandran Avatar answered Oct 15 '22 04:10

Ganesh Ramachandran