简体   繁体   English

Android服务未绑定

[英]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. 在onStart()方法中,我启动了服务并尝试将其绑定。 As you can see when it's been bound it will show me in the LogCat. 如您所见,绑定后它将在LogCat中向我显示。 However, it never does! 但是,它永远不会!

The Service itself will always be created and started (I put a Log.d(..) in both of the methods). 该服务本身将始终被创建和启动(我在两个方法中都放置了一个Log.d(..) )。

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. 问题出在onBind()方法中。 In order to bind to a service, you need to return an instance of binder there (not a null ) as described here . 为了绑定到服务,您需要在此处返回一个绑定器实例(不是null ),如此处所述

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 文档链接: http : //developer.android.com/guide/components/bound-services.html#Binder

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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