Androider
Androider

Reputation: 21335

Android Activity to Service Connection

Activities have handler methods on them like onClick for various UI events. How does one guarantee that the service connection exists for these methods? The service connection has an onServiceConnected method for initialization after the service has connected. However this seems like not the best place for UI initialization. I want to avoid onClick(View v) { service.getValue() } from being a null service reference. On the other hand I don't want the UI rendering to depend on waiting for a service reference. It seems that onCreate() is the right place for setContentView() etc. On the other hand onCreate is initializing handlers which might not be using a valid service reference yet. How does one guarantee that a service reference is valid for UI handler methods. Or is this a good reason not to use a service reference at all? Whats the best practice here?

Upvotes: 0

Views: 1723

Answers (2)

Mukul
Mukul

Reputation: 3

In the UI event listener, you could check if the service reference is null before using it:

if (service != null)
{
    service.getValue();
}

Upvotes: 0

Peter Knego
Peter Knego

Reputation: 80330

You have to signal to the Activity that Service is ready.

The simplest way would be to set a flag e.g. serviceAvailable = true, in ServiceConnection.onServiceConnected(). Then every time you need service you check this flag.

Upvotes: 3

Related Questions