Jac*_*nkr 1 java android callable
我一直在使用Callable,但现在我需要在该call方法中使用param的函数.我知道这不是一种能力,call我怎么能这样做?
我目前有什么(错误的):
AsyncTask async = new MyAsyncTask();
async.finished(new Callable(param) {
// the function called during async.onPostExecute;
doSomething(param);
});
async.execute(url);
Run Code Online (Sandbox Code Playgroud)
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;
}
...
Run Code Online (Sandbox Code Playgroud)
如果你创建param了一个最终变量,你可以从以下内容中引用它Callable:
final String param = ...;
async.finished(new Callable() {
// the function called during async.onPostExecute;
doSomething(param);
});
Run Code Online (Sandbox Code Playgroud)
你创建的时候必须这样做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);
Run Code Online (Sandbox Code Playgroud)
然后:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)