Saurabh
Saurabh

Reputation: 495

Handling services and sending data across activities

I'm trying to start a service from one activity to make an api call and obtain its result in another activity. I use a BroadcastReceiver to receive the data but how do I make sure that the activity is created and the receiver is attached before sending the broadcast from the service. Is there something wrong with the way that I'm designing this?

Thanks in advance.

Edit: To simply this, I'm starting a 3 second animation when the app is called. I do not want to waste that time and so I'm trying to get data from network and then display it on the activity called after the animation ends. I assumed IntentService would be the way to go but if its not please suggest me how to go about this.

Upvotes: 0

Views: 53

Answers (1)

Son Truong
Son Truong

Reputation: 14173

You can use Sticky Events from EventBus library. Basically it will cache your data in memory before broadcasting events. The data can be delivered to subscribers. Thus, you don’t need any special logic to consider already available data.

First you need to declare a class to hold data which you get from network.

public class MyDataEvent {
    String token;
    // Write more properties here
}

In the service, after getting the data from network, post event which contains data to subscribers.

MyDataEvent data = new MyDataEvent();
data.token = "123456789abcxyz";
EventBus.getDefault().postSticky(data);

In activity which you want to receive the data

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

// UI updates must run on MainThread
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onMyDataEvent(MyDataEvent data) {   
    // Process the data here
    Log.i("TAG", data.token);
}

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);    
    super.onStop();
}

Upvotes: 1

Related Questions