LoginSignup
0
0

More than 5 years have passed since last update.

Xamarin.Android でシステムボリュームが変更されたことを検知する

Posted at

teratail に投稿された質問への回答ですが、こちらにも貼っときます。

Stackoverflow の回答にある Java-Android のコードを、 Xamarin.Android 用に少し「書き換え」ただけです。

// MainActivity.cs
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Content;

namespace VolumeSample
{
    [Activity(Label = "VolumeSample", MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            this.ApplicationContext.ContentResolver.RegisterContentObserver(
                Android.Provider.Settings.System.ContentUri, true, 
                new VolumeObserver(this, new Handler()));
        }
    }

    internal class VolumeObserver : Android.Database.ContentObserver
    {
        private readonly Context context;

        public VolumeObserver(Context context, Handler handler) : base(handler)
        {
            this.context = context;
        }

        public override void OnChange(bool selfChange)
        {
            base.OnChange(selfChange);

            var audioManager = (Android.Media.AudioManager)context.GetSystemService(Context.AudioService);
            var volume = audioManager.GetStreamVolume(Android.Media.Stream.System);
            Toast.MakeText(context, 
                           $"Current System Vol: {volume}", 
                           ToastLength.Short).Show();
        }
    }
}

BroadcastReceiver を使うことでも実現できるようですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0