3

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);
}
Nerus
  • 167
  • 1
  • 2
  • 13
  • If anyone still looking for a solution I recently fixed the issue. Please look at my answer here: http://stackoverflow.com/a/26525889/513413 – Hesam Oct 24 '14 at 05:38

3 Answers3

7

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
    }
}
Jollyjagga
  • 196
  • 1
  • 3
  • 6
3

You should :

static public class doSomething implements Callable<Boolean> {

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

doSomething task = new doSomething ();
Future<Boolean> future = executor.submit(task);
Boolean res = future.get(); // get() will block waiting for result, so dont call it on UI thread

you will also have to catch ExecutionException, InterruptedException

as in Larry Schiefer answer, you should look into other - more android oriented solutions to acomplish it. If you need to maintain FTP connection then maybe Service will be better, if you need only to get results then AsyncTask or AsyncTaskLoader

marcinj
  • 48,511
  • 9
  • 79
  • 100
0

Look into using either AsyncTask, Loader or Handler objects to accomplish this.

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33