java - 传递使用参数的android函数

标签 java android callable

我一直在使用 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/

相关文章:

android - findViewByID(R.layout.skeleton_activity) 返回 null

python - "TypeError: native Qt signal is not callable"带有自定义插槽

Java 标记接口(interface)

java - jdom2 并从 URI 读取 xml 字符串而不是文件

java xpath 文本

java - 如何制作某个自定义 ListView 项目,将您发送到某个 Activity ?

java - GSON - 将空值反序列化为 "null "字符串

android - 无法为显示类转换异常的包含文件中存在的相对布局动态设置布局参数

java ExecutorService 如何处理超时

c++ - 指向成员函数的指针不是可调用对象