1

我一直在使用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;
}
...
4

2 回答 2

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();
        }
    }
}
于 2011-10-31T20:51:13.250 回答
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();
于 2013-08-28T17:20:19.330 回答