本文根据原生Android 4.1.1 Music 源码做修改。
1 原生Music 暂停的时候,会删除通知栏上的通知。
2 原生Music 通知栏不能控制音乐,比如下一首,上一首,暂停/播放。
一 解决思路:
1 接到暂停广播时,只暂停,不去除通知。
/packages/apps/Music/src/com/android/music/MediaPlaybackService.java中
调用的 stopForeground(true)方法控制去除通知
2 自定义音乐通知,添加按钮事件。
/packages/apps/Music/src/com/android/music/MediaPlaybackService.java中
updateNotification()方法中自定义Notification,关键对RemoteViews 的理解
二 修改后效果图:
三 详细代码
1 接到暂停广播时,只暂停,不去除通知
源代码 采取的策略是 只要暂停就去除通知,这就会造成一个问题就是,当播放视频的时候音乐播放器接受到暂停的广播,于是消除了通知栏。
1.1 添加暂停 不消除通知的方法 pause(boolean isStopForeground)
private void pause(boolean isStopForeground) {
synchronized(this) {
mMediaplayerHandler.removeMessages(FADEUP);
if (isPlaying()) {
mPlayer.pause();
gotoIdleState(isStopForeground);
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
private void gotoIdleState(boolean isStopForeground) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
//此方法控制消除通知
stopForeground(isStopForeground);
}
1.2 接收暂停广播的时候将pause()方法换为:pause(false)
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
MusicUtils.debugLog("mIntentReceiver.onReceive " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
gotoNext(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev()