开发者

How do I get an IBinder/ServiceConnection/onServiceConnected when starting a Service with startService?

开发者 https://www.devze.com 2023-04-12 09:08 出处:网络
I have been looking for some way to get the ServiceConnection when I start my Service using startService(...).

I have been looking for some way to get the ServiceConnection when I start my Service using startService(...).

I haven't found a way, so I have been searching a bit and found this: Does each Activity need to Bind to a Service & What happens when it was created with startService()

There, Commonsware says that it doesn't matter if I call bindService after the startService call.

So I thought that I first run startService(...) and then directly after do a bindService(...) (so that onServiceConnected is called). But then the Service.onCreate is executed twice. Probably because开发者_如何学编程 startService isn't "finished" yet...?

Question is: How do I get a reference to my Service (the IBinder), ie. how do I get the onServiceConnected to fire if I start my Service with startService?

--- EDIT ---

I still do want to know any answers and ideas you might have. I made a "hack" to get around this:

I simply made a static reference (in SRef.java I have public static IBinder myBinder = null), and in my Service.onCreate I simple do

SRef.myBinder = myBinder;

This doesn't seem right to me, so any other ideas on how it is supposed to work would be appreciated.


I use the exact same technique (a samba client service), onCreate is never called twice for me and I get the binder (by connection callback) as I would expect. A new start of activity doesn't fire a onCreate either because previous startService performed the startup of the service already.

Here is my code (might be trivial, but maybe it helps):

Activity (onCreate):

startService(new Intent(this, SambaService.class));
bindService(new Intent(this, SambaService.class), sambaServiceConnection,
        Context.BIND_AUTO_CREATE);

Service:

private ServiceBinder mServiceBinder = new ServiceBinder();

public class ServiceBinder extends Binder {
    public SambaService getService() {
        return SambaService.this;
    }
}

public IBinder onBind(Intent intent) {
    return mServiceBinder;
}
0

精彩评论

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

关注公众号