Handle multiple Intent Services within the same class (Receive data back from multiple services)

时间:2015-09-14 15:27:48

标签: android intentservice receiver

I have initialized 2 public Receiver variable at beginning of my register.class

public RegisterReceiver rReceiver;
public ConvertAddressToLatLongReceiver catllReceiver;

and then in onCreate() I defined them as follows

rReceiver = new RegisterReceiver(new Handler());
rReceiver.setReceiver(this);

catllReceiver = new ConvertAddressToLatLongReceiver(new Handler());
catllReceiver.setReceiver(this);

Both of these Receivers implement onReceiveResult() at the end of the class. Is there a way to distinguish which of the services is calling the onReceiveResult() fucntion like distinguishing between which buttons are clicked in onClick() ?

Edited: this is one of my Receiver classes.

import ca.amoh.track.trackingnetwork.interfaces.Receiver;


    public class RegisterReceiver extends ResultReceiver {

    private Receiver rReceiver;

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

    public void setReceiver(RegisterScreen rReceiver) {
        this.rReceiver = rReceiver;
    }

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

1 个答案:

答案 0 :(得分:1)

This is the structure of the onReceiveResult method:

protected void onReceiveResult(int resultCode, Bundle resultData) {
    super.onReceiveResult(resultCode, resultData);
}

Now you can either use the resultCode parameter to distinguish between two results or use the Bundle parameter with some marker information.

Edit

If you use the resultCode then it is slightly easy to switch between results:

protected void onReceiveResult(int resultCode, Bundle resultData) {
    switch(resultCode){
        case 100: \\ result from one receiver
             ...                 
        case 200: \\ result from another receiver
             ...
    }
}