简体   繁体   中英

Android service does not bind

@Override
protected void onStart(){
    super.onStart();
    Intent musicIntent = new Intent( this, MusicService.class );
    startService(musicIntent);
    getApplicationContext().bindService( musicIntent, mConnection, BIND_AUTO_CREATE);
}

private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mBound = false;
        mService = null;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mBound = true;
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        Log.d(TAG, "Bound");
    }
};

When I start a new activity I want to start a service as well and bind it so I can use some methods of that service. In the onStart() method I started the service and tried to bind it. As you can see when it's been bound it will show me in the LogCat. However, it never does!

The Service itself will always be created and started (I put a Log.d(..) in both of the methods).

Manifest file :

<service android:name="com.ppp.p.MusicService"></service>

What is wrong?

Edit :

@Override
public IBinder onBind(Intent intent) {
    return null;
}

Problem is in onBind() method. In order to bind to a service, you need to return an instance of binder there (not a null ) as described here .

public class LocalService extends Service {
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

}

You are returning a null binder. Add this to your service.

public class LocalBinder extends Binder {
    public MyService getService() {
        return MyService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

private final IBinder mBinder = new LocalBinder();

Documentation link: http://developer.android.com/guide/components/bound-services.html#Binder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM