Java – Android callable

Android callable… here is a solution to the problem.

Android callable

How do I implement Callable to return boolean values and do something?

I need to connect to the

FTP server using an external thread, I can’t do that in the main activity, I need a return value to know if it’s connected;

[main activity]

public class doSomething implements Callable<Boolean> {

@Override
   public Boolean call() throws Exception {
        TODO something...
       return value;
   }

}

public void onClick(View view) {
    ExecutorService executor = Executors.newFixedThreadPool(1);
    FutureTask<Boolean> futureTask = new FutureTask<Boolean>(new doSomething());
    executor.execute(futureTask);
}

Solution

You can use Callable in Android just like any other Java program, i.e.

    ExecutorService executor = Executors.newFixedThreadPool(1);
    final Future<Boolean> result = executor.submit(callable);
    boolean value = result.get()

But note that the get() method blocks the main thread, which is not recommended.

For your use case, you should use AsyncTask instead. For example,

public class FTPConnection extends AsyncTask<Void, Void, Boolean> {

@Override
    protected boolean doInBackground(Void... params) {
          Connect to FTP
    }

@Override
    protected void onPostExecute(boolean connected) {
         Take action based on result
    }
}

Related Problems and Solutions