Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onServiceConnected() not called

Tags:

I have a problem with using a background service.
I am using the service from 2 activities.

The first activity starts the Service with startService(intent) and the binds to it with bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

This works perfectly and I can send a Message in onServiceConnected().

The second activity only binds to the Service (since it's already started), again using bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

Now here is my problem:
In the second activity I have a Button which should use the service when I press it.
However, the onServiceConnected() is never called in this activity, so I can not get the binder to create a Messenger to send a Message to the server.

Does anyone know when onServiceConnected() is called exactly, or what it is possibly waiting for?
Or maybe something else to fix this problem?

EDIT: bindService returns false, what could cause this?

Thanks in advance

like image 576
Leon van Noord Avatar asked Oct 24 '11 11:10

Leon van Noord


People also ask

How to bind service to activity?

To provide binding for a service, you must implement the onBind() callback method. This method returns an IBinder object that defines the programming interface that clients can use to interact with the service.

When onServiceDisconnected is Called in Android?

This typically happens when the process hosting the service has crashed or been killed. This does not remove the ServiceConnection itself -- this binding to the service will remain active, and you will receive a call to onServiceConnected(ComponentName, IBinder) when the Service is next running. Ok.

What is ServiceConnection Android?

onServiceConnected(ComponentName name, IBinder service) Called when a connection to the Service has been established, with the IBinder of the communication channel to the Service. abstract void. onServiceDisconnected(ComponentName name) Called when a connection to the Service has been lost.


2 Answers

You need to add:

<service android:name="package.path.to.your.service.class" android:enabled="true"></service>

in the Android manifest file.

like image 81
Erdinc Ay Avatar answered Sep 17 '22 19:09

Erdinc Ay


After some more research, I discovered this is a known issue in Android.

The second activity I was talking about was an activity which is used as content within a TabActivity.

The way to fix this was to call bindService(...) on the application context, instead of on the activity context using getApplicationContext().bindService(...)

like image 21
Leon van Noord Avatar answered Sep 17 '22 19:09

Leon van Noord