[英]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");
}
};
当我启动一个新活动时,我也想启动一个服务并将其绑定,以便可以使用该服务的某些方法。 在onStart()方法中,我启动了服务并尝试将其绑定。 如您所见,绑定后它将在LogCat中向我显示。 但是,它永远不会!
该服务本身将始终被创建和启动(我在两个方法中都放置了一个Log.d(..)
)。
清单文件:
<service android:name="com.ppp.p.MusicService"></service>
怎么了?
编辑:
@Override
public IBinder onBind(Intent intent) {
return null;
}
问题出在onBind()
方法中。 为了绑定到服务,您需要在此处返回一个绑定器实例(不是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;
}
}
您将返回空的资料夹。 将此添加到您的服务。
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();
文档链接: http : //developer.android.com/guide/components/bound-services.html#Binder
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.