【问题标题】:pass android function that uses a param传递使用参数的android函数
【发布时间】:2011-12-19 01:27:06
【问题描述】:

我一直在使用Callable,但现在我需要在call 方法中使用参数的函数。我知道这不是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;
}
...

【问题讨论】:

    标签: java android callable


    【解决方案1】:

    如果您将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();
            }
        }
    }
    

    【讨论】:

    • 天哪,它是 Jon Skeet 又名 SOFLeBron James。我花了一秒钟才明白你对代码做了什么,但现在我明白了——它就像一个冠军。
    【解决方案2】:

    我创建了一个这样的新课程

    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();
    

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2015-06-19
      • 2019-06-13
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 2015-04-26
      相关资源
      最近更新 更多