Leonid
Leonid

Reputation: 71

Android Service PendingIntent no callback from Service in the Activity (Fragment)

I am trying to trigger the onActivityResult method from a Service using PendingIntent. Everything goes fine: background thread works perfectly, PendingIntent sends an Intent object to a Fragment, but it does not run the onActivityResult method.

Here is my code for Service creation:

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;
        }
    }
}

Service sending code:

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");
}

Upvotes: 1

Views: 1655

Answers (2)

Sergey Vlasov
Sergey Vlasov

Reputation: 1068

Using a PendingIntent from createPendingResult() to pass information from a service to an activity works — when the service calls pendingIntent.send(), the onActivityResult() method of the activity is invoked. However, there are some caveats:

  1. There is no way to get the onActivityResult() callback in a fragment — receiving the result must be handled directly in the activity.
  2. When the activity receiving the result is not running (e.g., the user switched to another app while the background operation was in progress), the onActivityResult() method will not be called immediately — instead, the data from all pendingIntent.send() calls will be queued, and when the activity is started again, it will receive all those queued onActivityResult() calls at once.

Upvotes: 0

Larry Schiefer
Larry Schiefer

Reputation: 15775

This is not the correct use of the Intent for result. That is only used when calling startActivityForResult() from one Activity to another. From your Service when you call pi.send() you are effectively doing a startActivity() with the contents of the PendingIntent.

Upvotes: 1

Related Questions