@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;
}
答案 0 :(得分:2)
问题出在onBind()
方法中。要绑定到服务,您需要在其中返回一个binder实例(不是null
)作为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;
}
}
答案 1 :(得分:1)
您正在返回null绑定器。将此添加到您的服务中。
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