Reputation: 71
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
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:
onActivityResult()
callback in a fragment — receiving the result must be handled directly in the activity.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
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