如何实现Callable返回 boolean 值并做点什么?
我需要使用外部线程连接到 FTP 服务器,我不能在主要 Activity 中这样做,我需要返回值来知道它是否已连接;
[主 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);
}
Best Answer-推荐答案 strong>
您可以像在任何其他 Java 程序中一样在 Android 中使用 Callable,即
ExecutorService executor = Executors.newFixedThreadPool(1);
final Future<Boolean> result = executor.submit(callable);
boolean value = result.get()
但请注意,get() 方法会阻塞主线程,不建议这样做。
对于您的用例,您应该使用 AsyncTask反而。例如,
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
}
}
关于java - 安卓可调用,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/21002080/
|