0

I am currently working on webservice calls from my Android application. The calls and results are handled within an IntentService. For now, I'm using a class (MyReceiver) which extends from ResultReceiver.

public class ResultReceiverWS extends ResultReceiver {
    private Receiver mReceiver;

    public ResultReceiverWS(Handler handler) {
        super(handler);
    }

    public void setReceiver(Receiver receiver) {
        mReceiver = receiver;
    }

    public interface Receiver {
        public void onReceiveResult(int resultCode, Bundle resultData);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        if (mReceiver != null) {
            mReceiver.onReceiveResult(resultCode, resultData);
        }
    }
}

I pass from the Activity which implements MyReceiver.Receiver the instance of the class in a bundle like above code :

MyReceiver receiver = new MyReceiver (new Handler());
receiver.setReceiver(this);
Intent call = new Intent(getApplicationContext(), ClientWS.class);
call.putExtra(RECEIVER, receiver);
call.putExtra(ACTION, MYMETHOD);
startService(call);

The problem is that receiver is attached to the Activity thread, if activity is killed, re-created (by turning screen or whatever), receiver points in no man's land ...

So, my question is how to handle this cases. I've thinked about BroadcastReceiver but I'm not sure about that.

Any suggestions are welcome here.

Bibu
  • 1,249
  • 2
  • 17
  • 40

1 Answers1

1

Use LocalBroadcastManager.

Or, use a third-party event bus, like Otto or EventBus.

Or, if the result of this Web service call will only ever be used by the activity that requested it, switch to an AsyncTask managed by a retained fragment, in which case you can work with the UI more naturally.

Or, if you need to let the user know about the results even if your UI is not in the foreground, use the ordered broadcast pattern.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks a lot CommonsWare, will try the last of your proposal and be back to you if I have any questions about that, otherwise I will set this question as resolved ! – Bibu Jun 28 '13 at 12:05
  • 1
    @Bibu: You can find a sample implementation of that pattern at: https://github.com/commonsguy/cw-omnibus/tree/master/Notifications/Ordered – CommonsWare Jun 28 '13 at 12:07
  • Event buses (more specifically [LocalBroadcastManager](https://developer.android.com/reference/androidx/localbroadcastmanager/content/LocalBroadcastManager)) are deprecated – luismiguelss Nov 16 '21 at 12:59
  • @luismiguelss: So is `IntentService`. This question and answer are over 8 years old, and things have changed over the years. – CommonsWare Nov 16 '21 at 13:04
  • That's why I commented that out, in case anyone will see this @CommonsWare. – luismiguelss Nov 16 '21 at 13:55