Android Callable

Nerus picture Nerus · Jan 8, 2014 · Viewed 9.1k times · Source

How to implement Callable to return boolean and do something ?

I need use external Thread to connect to FTP server, I can't do this in main activity and I need return value to know it's connected or not;

[MainActivity]

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);
}

Answer

Jollyjagga picture Jollyjagga · Jan 8, 2014

You can use Callable in Android as you would in any other Java program, i.e

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

But be aware that the get() method would block 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
    }
}