android - `doInBackground()` 不接受类型为 void 的 `AsyncTask`?

标签 android android-asynctask

Google's Android Documentation 可以看出我们看到了

Params, the type of the parameters sent to the task upon execution.

Progress, the type of the progress units published during the background computation.

Result, the type of the result of the background computation.

也在this中提到很好的答案。

但是,为什么将 Void 作为结果类型会导致 Android Studio 在 doInBackground 行发出以下警告:

doInBackground(String...)' in '(..)MainActivity.myTask' clashes with 'doInBackground(Params...)' in 'android.os.AsyncTask'; attempting to use incompatible return type

AsyncTask 是这样声明的:

private class myTask extends AsyncTask<String,Void,Void> {
    @Override
    protected void doInBackground(String... url) {
        //do stuff with url[0]
    }

    @Override
    protected void onPostExecute() {
        //more stuff
    }
}

相比之下,这似乎工作正常:

private class myTask extends AsyncTask<String,Void,String> {
    @Override
    protected String doInBackground(String... url) {
        //do stuff with url[0]
        return "hi";
    }

    @Override
    protected void onPostExecute(String result) {
        //more stuff
    }
}

请注意,关于这个主题有各种各样的问题,但大多数只是搞乱了类中的 AsyncTask 参数或参数和返回值。

最佳答案

试试这段代码

 private class myTask extends AsyncTask<String,Void,Void> {
    @Override
    protected Void doInBackground(String... url) {
          //do stuff with url[0]
        return null;

    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        //more stuff
    }
}

关于android - `doInBackground()` 不接受类型为 void 的 `AsyncTask`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38993601/

相关文章:

android - React-Native:-如何在单个目录中为 android 的不同分辨率提供图像

android - 菜单项在操作栏中移动

java - 关于 Bitmap 以不同方式转换为 ByteArray 的困惑

Android:如何从状态栏通知创建的 PendingIntent 访问 AsyncTask?

android - AsyncTask 和 listActivity

java - 适用于 Android 的 Lib Panorama Spherical

java - 在 xml 中创建的字符串数组与在 Java 类中初始化的字符串数组有什么区别

java - 如何更改进度对话框文本

android - 从 AsyncTask Android 返回数据

android - Android 适配器中的错误 java.lang.IndexOutOfBoundsException : Invalid index 0, 大小为 0