开发者

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 开发者_如何学Gothe 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?


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜