我一直在使用Callable
,但现在我需要该函数在call
方法中使用param。我知道这不是call
的能力所以我怎么能这样做?
我目前有什么(错误的):
AsyncTask async = new MyAsyncTask();
async.finished(new Callable(param) {
// the function called during async.onPostExecute;
doSomething(param);
});
async.execute(url);
MyAsyncTask:
...
@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;
}
...
答案 0 :(得分:5)
如果您将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();
}
}
}
答案 1 :(得分:0)
我创建了一个像这样的新课程
import java.util.concurrent.Callable;
public abstract class ParamCallable<T> implements Callable<T> {
public String Member; // you can add what you want here, ints, bools, etc.
}
然后你所要做的就是
ParamCallable<YourType> func = new ParamCallable<YourType>() {
public YourType call() {
// Do stuff.
// Reference Member or whatever other members that you added here.
return YourType;
}
}
然后当你调用它时,设置你的数据并调用call()
func.Member = value;
func.call();