Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, unbind service and onServiceDisconnected problem

I'm not good in English, but I would try to explain my problem in good way.

So, the problem is:
1) I have a local service
2) I start it and then bound to it. 3) Problem appears when I am about to close that service. onServiceDisconnected method from my implementation of class ServiceConnection is never called. If I close it manually (from settings), or by unbindService, or by stopService, or by combination of unbindService and stopService - onServiceDisconnected still doesn't to be called. What am I doing wrong?

Short code is below:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(i, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(i);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

I'm testing this code under emulator of Android 2.2

like image 637
UAS Avatar asked Mar 13 '11 22:03

UAS


People also ask

What is bind and unbind service in Android?

It allows components (such as activities) to bind to the service, send requests, receive responses, and perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.

How do you unbind a service?

To unbind a service, use the unbind lb vserver command instead of bind lb vserver .


1 Answers

onServiceDisconnected is only called in extreme situations (crashed / killed).

which is very unlikely to happen for a local service since all your application components normally run in the same process... meaning, unless you intentionnaly unbind or destroy the service, it should remain connected, or die with the component using it.

like image 155
darma Avatar answered Nov 15 '22 18:11

darma