Skip to content

Instantly share code, notes, and snippets.

@Osmosis311
Created January 22, 2023 02:30
Show Gist options
  • Save Osmosis311/0be8cb4b400c97618b39b394024dba10 to your computer and use it in GitHub Desktop.
Save Osmosis311/0be8cb4b400c97618b39b394024dba10 to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Media;
namespace MemberApp.Droid
{
public class PushReceiver : BroadcastReceiver
{
public async override void OnReceive(Context context, Intent intent)
{
String custom = intent.GetStringExtra("custom").ToString();
// Check here to see if the payload indicates that the sound should be played
await PlaySound(context);
}
async Task PlaySound(Context context)
{
var am = (AudioManager)Application.Context.GetSystemService(Context.AudioService);
var tcs = new TaskCompletionSource<object>();
int currentVolume = am.GetStreamVolume(Stream.Music);
int maxVolume = am.GetStreamMaxVolume(Stream.Music);
var handler = new EventHandler((sender, args) => tcs.TrySetResult(null));
MediaPlayer mediaPlayer = null;
try
{
mediaPlayer = MediaPlayer.Create(context, Resource.Raw.emergency);
am.SetStreamVolume(Stream.Music, maxVolume, VolumeNotificationFlags.PlaySound);
mediaPlayer.Completion += handler;
mediaPlayer.Start();
await tcs.Task.ConfigureAwait(false);
}
finally
{
if (mediaPlayer != null)
{
am.SetStreamVolume(Stream.Music, currentVolume, VolumeNotificationFlags.PlaySound);
mediaPlayer.Completion -= handler;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment