【问题标题】:How to pass the return value of an AsyncTask callback to another class properly without get() method?如何在没有 get() 方法的情况下正确地将 AsyncTask 回调的返回值传递给另一个类?
【发布时间】:2014-05-13 17:08:47
【问题描述】:

在我的应用程序中,我需要调用 Web 服务以从 Internet 获取一些数据。为了避免阻塞 UI,我使用 AsyncTask 来做到这一点。但是我在正确传递返回值以供进一步使用时遇到问题。我想我在这里犯了一些架构错误。所以这就是我的应用程序的结构/应该是这样的:

MainActivity:一个Activity,包含一个TextView、一个Button和一个SoapParser(见下文)。我想通过按Button调用Web服务,解析结果并显示在TextView中。

SoapRequestTask:具有类似this 的回调机制的AsyncTaskdoInBackground()的返回值为SoapObject,在onPostExecute()中的回调方法listener.onTaskCompleted(SoapObject)中作为参数传递给监听器。

SoapRequestManager:应该有一个方法public SoapObject makeRequest(someParams)的类。这个方法应该使用我的AsyncTask 并从它的doInBackground() 返回我的SoapObject

MySpecialRequestManager:扩展SoapRequestManager,并有不同的方法来调用Web服务以获得不同的结果。这些方法中的每一个都使用超类的makeRequest(someParams)

SoapParser:一个将SoapObject解析为String的类,因此它可以显示在我的ActivityTextView中。它应该有一个类似public String parseResult(SoapObject)的方法。

如何正确使用回调和返回值?哪个类应该实现回调接口?

【问题讨论】:

  • 让 SoapRequestManager 实现 BroadcastReceiver 并发送一个广播,让它接收包含有问题数据的包。
  • @zgc7009 能给我一个代码示例吗?

标签: android android-asynctask callback return-value


【解决方案1】:

只是一个快速的 sn-p,因为您要求一些代码。这可能有助于您开始

在 SoapRequestTask 的 AsyncTask 的 postExecute() 方法中

Intent intent = new Intent("send_data");
intent.setAction("SEND_DATA");              // don't NEED this, as we implicitly
                                            // declare our intent during initialization
intent.putExtra("data_return_key", mData);  // where mData is what you want to return
sendBroadcast(intent);

那么对于 SoapRequestManager

public class SoapRequestManager implements BroadcastReceiver{
    int mData;                        // assuming our data is an int in this example

    // Default constructor
    public SoapRequestManager(){
        registerReceiver(this, new IntentFilter("send_data"));
        // if you use setAction use the below registration instead
        // registerReceiver(this, new IntentFilter("SEND_DATA"));
    }

    //... All of the stuff you have in the class already

    @Override
    public void onReceive(Context context, Intent intent){
        // For this example let's say mData is an integer value

        // if you use setAction, check that the intent is the correct one via
        // if (intent.getAction().equals("SEND_DATA"))
        mData = intent.getIntExtra("data_return_key");
    }
}

【讨论】:

    猜你喜欢
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2017-05-06
    • 2021-12-19
    • 2018-12-24
    • 1970-01-01
    • 2020-01-03
    相关资源
    最近更新 更多