java 在 Android 中不向 AsyncTask 传递任何内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7635902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:47:13  来源:igfitidea点击:

Passing nothing to an AsyncTask in Android

javaandroidandroid-asynctask

提问by Ben Taliadoros

How do I instantiate and call and class extending AsyncTask if I am passing nothing to it?

如果我没有向 AsyncTask 传递任何内容,我该如何实例化、调用和类扩展 AsyncTask?

Also, I am setting a textview in the UI to the calculated result.

另外,我在 UI 中将 textview 设置为计算结果。

Thanks, Ben

谢谢,本

回答by d.danailov

Example implementation for Async without params and result Bitmap in onPostExecute result

无参数异步的示例实现和 onPostExecute 结果中的结果位图

/**
 * My Async Implementation without doInBackground params
 * 
 */
private class MyAsyncTask extends AsyncTask<Void, Void, Bitmap> {

    @Override
    protected Bitmap doInBackground(Void... params) {

        Bitmap bitmap;

        .... 

        return bitmap;
    }

    protected void onPostExecute(Bitmap bitmap) {

        ....
    }
}

In your activity, you should to add this implementation:

在您的活动中,您应该添加此实现:

MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();

回答by Lars

I think what you meant to ask was how do I write an AsyncTask that doesn't ask for any parameters. The trick is to define what you expect to use as parameter and return value in the extension of your class: class MyClass extends AsyncTask<Void, Void, Void>for example doesn't expect any parameters and doesn't return any either. AsyncTask<String, Void, Drawable>expects a String (or multiple strings) and returns a Drawable (from its own doInBackgroundmethod to its own onPostExecutemethod)

我想你想问的是我如何编写一个不要求任何参数的 AsyncTask 。诀窍是定义您希望在类的扩展中用作参数和返回值的内容: class MyClass extends AsyncTask<Void, Void, Void>例如,不需要任何参数,也不返回任何参数。 AsyncTask<String, Void, Drawable>期望一个字符串(或多个字符串)并返回一个 Drawable(从它自己的doInBackground方法到它自己的onPostExecute方法)