Я решил создать класс для проекта Droid следующим образом:
class NotificationManager
{
static public Android.Media.AudioManager audioManager = null;
static Activity mainActivity = null;
public static Activity MainActivity
{
set { mainActivity = value; }
}
Android.Media.AudioManager.IOnAudioFocusChangeListener listener = null;
private class FocusChangeListener : Java.Lang.Object, Android.Media.AudioManager.IOnAudioFocusChangeListener
{
public void OnAudioFocusChange(AudioFocus focusChange)
{
switch (focusChange)
{
// We will take any flavor of AudioFocusgain that the system gives us and use it.
case AudioFocus.GainTransient:
case AudioFocus.GainTransientMayDuck:
break;
case AudioFocus.Gain:
break;
// If we get any notificationthat removes focus - just terminate what we were doing.
case AudioFocus.LossTransientCanDuck:
break;
case AudioFocus.LossTransient:
case AudioFocus.Loss:
break;
default:
break;
}
}
}
public Boolean RequestAudioResources()
{
listener = new FocusChangeListener();
var ret = audioManager.RequestAudioFocus(listener, Stream.Music, AudioFocus.GainTransientMayDuck);
if (ret == AudioFocusRequest.Granted)
{
return (true);
}
else if (ret == AudioFocusRequest.Failed)
{
return (false);
}
return (false);
}
public void ReleaseAudioResources()
{
if (listener != null)
audioManager.AbandonAudioFocus(listener);
}
}
Затем в MainActivity я установил:
NotificationManager.audioManager = (Android.Media.AudioManager)GetSystemService(Context.AudioService);
NotificationManager.MainActivity = this;
На данный момент я могу управлять звуком, вызывая методы RequestAudioResources () и ReleaseAudioResources ().
Когда аудио-фокус изменяется, вызывается метод OnAudioFocusChange (), и вы можете делать больше вещей.