MediaPlayer C++实现在libmedia里面,和MediaPlayer.java对应起来,这两者之间通过jni实现android_media_MediaPlayer.cpp联系起来,setDataSource的时候,MediaPlayer会先获取MediaplayerService,然后通过service的create创建MediaPlayerService::Client,MediaPlayer中的
mPlayer就是创建的MediaPlayerService::Client对象。
BP(binder proxy)和BN(binder native)是通过binder来通信的,Bp端可以通过BinderProxy的transact()方法与Bn端发送请求,而Bn端通过继承Binder类并重写onTransact()接收并处理来自Bp端的请求。
Bn意味着Binder Native端,Bp是Binder Proxy端,Bn端通过onTransact()方法接收来自Bp端的请求的代码,然后把结果写入reply,Bp端再从reply中读取返回值并返回给调用者。
MediaPlayer::setDataSource:
status_t MediaPlayer::setDataSource(const sp&source) { ALOGV("setDataSource(IDataSource)"); status_t err = UNKNOWN_ERROR; const sp service(getMediaPlayerService()); if (service != 0) { sp player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(source))) { player.clear(); } err = attachNewPlayer(player); } return err; }
调用BpMediaPlayerService:: create:
virtual spcreate( const sp & client, audio_session_t audioSessionId) { Parcel data, reply; data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor()); data.writeStrongBinder(IInterface::asBinder(client)); data.writeInt32(audioSessionId); remote()->transact(CREATE, data, &reply); return interface_cast (reply.readStrongBinder()); }
BnMediaPlayerService::onTransact里面创建调用create:
status_t BnMediaPlayerService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch (code) {
case CREATE: {
CHECK_INTERFACE(IMediaPlayerService, data, reply);
sp client =
interface_cast(data.readStrongBinder());
audio_session_t audioSessionId = (audio_session_t) data.readInt32();
sp player = create(client, audioSessionId);
reply->writeStrongBinder(IInterface::asBinder(player));
return NO_ERROR;
} break;
MediaPlayerService::create:
spMediaPlayerService::create(const sp & client, audio_session_t audioSessionId) { pid_t pid = IPCThreadState::self()->getCallingPid(); int32_t connId = android_atomic_inc(&mNextConnId); // MediaPlayerService::Client sp c = new Client( this, pid, connId, client, audioSessionId, IPCThreadState::self()->getCallingUid()); ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid, IPCThreadState::self()->getCallingUid()); wp w = c; { Mutex::Autolock lock(mLock); mClients.add(w); } return c; }
然后MediaPlayer持有了MediaPlayerService:: Client对象,player相关的所有操作都是通过这个Client对象完成的。



