我一直在使用 Callable
,但现在我需要在 call
方法中使用参数的函数。我知道这不是 call
的功能,那么我该怎么做呢?
我目前拥有的(错误的):
AsyncTask async = new MyAsyncTask();
async.finished(new Callable(param) {
// the function called during async.onPostExecute;
doSomething(param);
});
async.execute(url);
我的异步任务:
...
@Override
protected void onPostExecute(JSONObject result) {
//super.onPostExecute(result);
if(result != null) {
try {
this._finished.call(result); // not valid because call accepts no params
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void finished(Callable<Void> func) {
this._finished = func;
}
...
最佳答案
如果您将 param
设置为最终变量,您可以在 Callable
中引用它:
final String param = ...;
async.finished(new Callable() {
// the function called during async.onPostExecute;
doSomething(param);
});
不过,当您创建 Callable
时,您必须执行此操作 - 您以后无法为其赋值。如果出于某种原因需要它,则基本上必须使用共享状态 - Callable
可以访问的一些“持有者”,并且可以在 之前将值设置到其中Callable
执行。这可能只是 MyAsyncTask
本身:
final MyAsyncTask async = new MyAsyncTask();
async.finished(new Callable() {
// the function called during async.onPostExecute;
doSomething(async.getResult());
});
async.execute(url);
然后:
private JSONObject result;
public JSONObject getResult() {
return result;
}
@Override
protected void onPostExecute(JSONObject result) {
this.result = result;
if(result != null) {
try {
this._finished.call();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
关于java - 传递使用参数的android函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7959533/