【问题标题】:Android Service PendingIntent no callback from Service in the Activity (Fragment)Android Service PendingIntent 没有从 Activity (Fragment) 中的 Service 回调
【发布时间】:2015-01-13 20:52:12
【问题描述】:

我正在尝试使用PendingIntentService 触发onActivityResult 方法。 一切正常:后台线程完美运行,PendingIntentIntent 对象发送到Fragment,但它没有运行onActivityResult 方法。

这是我创建Service 的代码:

Intent i = new Intent(getActivity(), UpdaterService.class);
Intent ei = new Intent();
PendingIntent pi = getActivity().createPendingResult(TASK_CODE_UPDATE, ei, 0);

onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "Result get");
    if(resultCode == RESULT_START){
        switch(requestCode){
        case TASK_CODE_UPDATE:
            lessonTextView.setText(data.getStringExtra(UpdaterService.EXTRA_LESSON_VIEW_TEXT));
            futureTextView.setText(data.getStringExtra(UpdaterService.EXTRA_FUTURE_VIEW_TEXT));
            break;
        }
    }
}

服务发送代码:

Intent i = new Intent()
    .putExtra(EXTRA_LESSON_VIEW_TEXT, lessonViewText)
    .putExtra(EXTRA_FUTURE_VIEW_TEXT, futureViewText);
try {
    pi.send(UpdaterService.this, HelperFragment.RESULT_START, i);
    Log.d(TAG, "Sending intent");
} catch (CanceledException e) {
    e.printStackTrace();
    Log.e(TAG, "Error sending intent");
}

【问题讨论】:

  • 我不知道 createPendingResult() 方法,所以我无法评论它为什么不起作用,但您可能应该改用 binding
  • 要将信息从您的Service 发送回您的Activity,您可以使用带有回调接口的绑定服务,也可以将结果作为广播发送Intent(使用@987654337 @) 并让您的 Activity 注册 BroadcastReceiver 以获得结果。

标签: android android-intent android-fragments service android-pendingintent


【解决方案1】:

这不是Intent 的正确使用结果。这仅在从一个Activity 调用startActivityForResult() 到另一个时使用。从您的Service 调用pi.send() 时,您实际上是在使用PendingIntent 的内容执行startActivity()

【讨论】:

    【解决方案2】:

    使用来自createPendingResult()PendingIntent 将信息从服务传递到活动是有效的——当服务调用pendingIntent.send() 时,将调用活动的onActivityResult() 方法。但是,有一些警告:

    1. 无法在片段中获取 onActivityResult() 回调 - 必须直接在 Activity 中处理接收结果。
    2. 当接收结果的 Activity 没有运行时(例如,用户在后台操作正在进行时切换到另一个应用程序),onActivityResult() 方法不会立即被调用——而是来自所有 pendingIntent.send() 的数据呼叫将被排队,当 Activity 再次启动时,它将立即接收所有排队的 onActivityResult() 呼叫。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多