【问题标题】:Waiting result of a task/service in a FragmentDispatcher在 FragmentDispatcher 中等待任务/服务的结果
【发布时间】:2016-06-15 23:34:05
【问题描述】:

我目前面临一个问题:我需要等待请求的结果才能返回一个值。这是我的 FragmentDispatcher 类的示例

public static Fragment getFragment(){
    switch (value) {
      case "1":
        // returns a fragment
        break;

      case "2":
        // returns another fragment
        break;

      case "3":
        // returns the correct fragment according to an async task or a Service response value
      break;
    }
    // returns default fragment
}

我的情况是第三种:我需要等待任务或服务完成才能根据异步任务的响应值返回片段(实际上是一个布尔值)。由于异步任务是..异步的,我的函数立即返回默认片段。

有人帮忙解决吗?

【问题讨论】:

  • 等待异步请求的结果通常会破坏首先使请求异步的目的。例如,如果您在 uI 线程上尝试这样做,您将收到 Application Not Responding 错误。你将不得不改变你的设计。例如,此方法可以返回 null 表示“我不知道是什么片段”,并且异步任务的结束可能会触发某种重试。这可能是一个太大的变化,无法在 Stack Overflow 答案(或评论!)中涵盖!
  • 感谢您的评论,我同意使用异步任务是一种非常糟糕的方式。我还提到过 Service 或 IntentService 呢?由于 onEventMainThread 方法,有什么方法可以使用我们在类中捕获的 EventBus 检索结果?

标签: android android-intent android-asynctask


【解决方案1】:

我通过在 AsyncTask 中调用 getFragment() 方法解决了我的问题。完成后,我在 postExecute() 中启动片段

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2019-02-24
    • 2019-06-12
    相关资源
    最近更新 更多