@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");
}
};
当我启动一个新 Activity 时,我也想启动一个服务并绑定(bind)它,以便我可以使用该服务的一些方法。在 onStart() 方法中,我启动了服务并尝试绑定(bind)它。正如你所看到的,当它被绑定(bind)时,它会在 LogCat 中向我显示。然而,它永远不会!
服务本身将始终被创建和启动(我在这两个方法中都放置了 Log.d(..)
)。
list 文件:
<service android:name="com.ppp.p.MusicService"></service>
出了什么问题?
编辑:
@Override
public IBinder onBind(Intent intent) {
return null;
}
最佳答案
问题出在 onBind()
方法中。为了绑定(bind)到服务,您需要在那里返回一个绑定(bind)器实例(不是 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;
}
}
关于java - Android服务未绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24597277/