Reputation: 623
I start a service in my Activity following way. After the Service started I close the Activity. If I start the Activity again, I want to receive some informations from the service. How can I do that?
// Activity
@Override
public void onCreate(Bundle savedInstanceState)
{
// here I want to receive data from Service
}
Intent i=new Intent(this, AppService.class);
i.putExtra(AppService.TIME, spinner_time.getSelectedItemPosition());
startService(i);
// Service
public class AppService extends Service {
public static final String TIME="TIME";
int time_loud;
Notification note;
Intent i;
private boolean flag_silencemode = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
time_loud = intent.getIntExtra(TIME, 0);
play(time_loud);
return(START_NOT_STICKY);
}
Upvotes: 0
Views: 137
Reputation: 7105
I would suggest using the Otto library from Square.
Otto is an event bus designed to decouple different parts of your application while still allowing them to communicate efficiently.
The simple way would be that you create a Bus:
Bus bus = new Bus();
Then you would simply publish an event:
bus.post(new AnswerAvailableEvent(42));
to which your Service
is subscribed
@Subscribe public void answerAvailable(AnswerAvailableEvent event) {
// TODO: React to the event somehow!
}
and then the service would provide a result
@Produce public AnswerAvailableEvent produceAnswer() {
// Assuming 'lastAnswer' exists.
return new AnswerAvailableEvent(this.lastAnswer);
}
Upvotes: 2
Reputation: 1006744
The simplest solution nowadays, IMHO, is to use a third-party event bus, like Square's Otto (using a @Producer
to allow the activity to get the last-sent event of a given type) or greenrobot's EventBus (using a sticky event to allow the activity to get the last-sent event of a given type).
Upvotes: 2