原
您的媒体会话回调会调用多个API中的方法来控制播放器,管理音频焦点以及与媒体会话和媒体浏览器服务进行通信。下表总结了这些任务如何在回调中分布。
以下是回调的示例框架:
private IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
// Defined elsewhere...
private AudioManager.OnAudioFocusChangeListener afChangeListener;
private BecomingNoisyReceiver myNoisyAudioStreamReceiver = new BecomingNoisyReceiver();
private MediaStyleNotification myPlayerNotification;
private MediaSessionCompat mediaSession;
private MediaBrowserService service;
private SomeKindOfPlayer player;
MediaSessionCompat.Callback callback = new
MediaSessionCompat.Callback() {
@Override
public void onPlay() {
AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback, this registers the afChangeListener
int result = am.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Start the service
service.start();
// Set the session active (and update metadata and state)
mediaSession.setActive(true);
// start the player (custom call)
player.start();
// Register BECOME_NOISY BroadcastReceiver
registerReceiver(myNoisyAudioStreamReceiver, intentFilter);
// Put the service in the foreground, post notification
service.startForeground(myPlayerNotification);
}
}
@Override
public void onStop() {
AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
// Abandon audio focus
am.abandonAudioFocus(afChangeListener);
unregisterReceiver(myNoisyAudioStreamReceiver);
// Start the service
service.stop(self);
// Set the session inactive (and update metadata and state)
mediaSession.setActive(false);
// stop the player (custom call)
player.stop();
// Take the service out of the foreground
service.stopForeground(false);
}
@Override
public void onPause() {
AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
// Update metadata and state
// pause the player (custom call)
player.pause();
// unregister BECOME_NOISY BroadcastReceiver
unregisterReceiver(myNoisyAudioStreamReceiver, intentFilter);
// Take the service out of the foreground, retain the notification
service.stopForeground(false);
}
}
注意:如果您使用必要的回叫功能创建MediaSession,那么使用Google智能助理的人可以使用语音命令来控制您的应用。这些要求在Google智能助理文档中进行了解释 。
联系我
QQ:94297366
微信打赏:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ
公众号推荐: