音乐播放器的主要服务如下
packages/apps/SnapdragonMusic/src/com/android/music/MediaPlaybackService.java
其注册对外部存储的监控如下:
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
if (mCurrentTrackInfo != null ) {
String curTrackPath = mCurrentTrackInfo.mData;
// if the currently playing track is on the SD card
if (curTrackPath != null && curTrackPath.contains(intent.getData().getPath())) {
saveQueue(true);
mQueueIsSaveable = false;
closeExternalStorageFiles(intent.getData().getPath());
}
}
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
// when play music in background, delete file in filemanager will not effect music to play
if (intent.getStringExtra("FileChange") != null) {
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
return;
}
mMediaMountedCount++;
mCardId = MusicUtils.getCardId(MediaPlaybackService.this);
// pause playback
pause();
reloadQueue();
mQueueIsSaveable = true;
notifyChange(PLAYSTATE_CHANGED);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
} else if (action.equals(ACTION_DELETE_MUSIC)) {
long id = intent.getLongExtra("mid", -1);
long artindex = intent.getLongExtra("artindex", -1);
if (id != -1 && artindex != -1) {
MusicUtils.deleteTrack(MediaPlaybackService.this, id, artindex);
}
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addAction(ACTION_DELETE_MUSIC);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
其中,挂载OTG U盘的监听事件是:Intent.ACTION_MEDIA_MOUNTED
从其实现的过程中可以找到:
// pause playback
pause();
reloadQueue();
mQueueIsSaveable = true;
notifyChange(PLAYSTATE_CHANGED);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
pause即为将音乐停止的函数。其他的会对消息队列有更新处理.