Skip to content

Instantly share code, notes, and snippets.

@madhu314
Created September 20, 2012 17:08
Show Gist options
  • Save madhu314/3757099 to your computer and use it in GitHub Desktop.
Save madhu314/3757099 to your computer and use it in GitHub Desktop.
Asynchronous exception communication between Service and UIComponent in Android
//lets say you have service XYService and a UI component XYFragment
//this piece of code goes in XYFragment
Intent serviceIntent = new Intent(context, XYService.class);
// add result receiver
serviceIntent.putExtra(XYService.RESULT_RECEIVER, new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// receive the result for this call
if (resultCode == XYService.RESULT_SUCCESSFUL) {
// np problem get the bundle data, if needed
} else {
Exception e = (Exception) resultData.getSerializable(XYService.FAILURE_EXCEPTION));
Log.e(TAG, "Service operation failed", e);
}
super.onReceiveResult(resultCode, resultData);
}
};);
getActivity().startService(serviceIntent);
//this is what goes in XYService
ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
try {
//try network operation
} catch(Exception e) {
Bundle resultData = new Bundle();
resultData.putSerializable(FAILURE_EXCEPTION, e);
receiver.send(RESULT_FAILED, resultData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment