所以我正在构建我的MusicPlayer,因此我创建了一个管理所有内容的服务。我致电ContextWrapper.bindService()
,这应该致电onServiceConnected
和onBind
吗?但对我来说情况并非如此。
如果我在那里遇到任何问题,请告诉我。
这是我的代码:
这是我将Activity绑定到服务(MusicUtils.java)的方法。在我的Activity中它看起来像这样:MusicUtils.bindToService(this,this);
public static final ServiceToken bindToService(final Context context,
final ServiceConnection callback) {
Activity realActivity = ((Activity)context).getParent();
if (realActivity == null) {
realActivity = (Activity)context;
}
final ContextWrapper contextWrapper = new ContextWrapper(realActivity);
contextWrapper.startService(new Intent(contextWrapper, MediaPlayerService.class));
final ServiceBinder binder = new ServiceBinder(callback);
Intent intent = new Intent().setClass(contextWrapper, MediaPlayerService.class);
if (contextWrapper.bindService(intent, binder, Context.BIND_AUTO_CREATE)) {
mConnectionMap.put(contextWrapper, binder);
Log.e("MusicUtils","Bound");
return new ServiceToken(contextWrapper);
}
return null;
}
这是我的ServiceBinder:
public static final class ServiceBinder implements ServiceConnection {
private final ServiceConnection mCallback;
public ServiceBinder(final ServiceConnection callback) {
mCallback = callback;
}
@Override
public void onServiceConnected(final ComponentName className, final IBinder service) {
mService = IMusicSlideService.Stub.asInterface(service);
if (mCallback != null) {
mCallback.onServiceConnected(className, service);
}
}
@Override
public void onServiceDisconnected(final ComponentName className) {
if (mCallback != null) {
mCallback.onServiceDisconnected(className);
}
mService = null;
}
}
这是我的onBind(MediaPlayerService.java):
@Override
public IBinder onBind(Intent intent) {
Log.e("Service", "onBind");
return mBinder;
}
如果您需要什么,请告诉我!
感谢!!!
答案 0 :(得分:0)
我使用下面的代码,一切正常。
Intent intent = new Intent(mContext, Connector.class);
mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
可能是你的问题在于使用ContextWrapper?
或尝试更改新的Intent()。setClass(contextWrapper,MediaPlayerService.class);到新的Intent(contextWrapper,MediaPlayerService.class);