简体   繁体   中英

Android C#:Listening for Volume button presses in background service

I'm creating an Android App in C# Xamarin.

Is there a way to "listen" for volume up/down key presses when an App goes into "background" mode, ie when a user "locks" their phone?

I've created several Service objects and made them "resident" by issuing the command 'StartCommandResult.Sticky'.

Any sample C# Xamarin code would be much appreciated.

You do not need to create a background service, just start a another task to listen the volume control. If the application do not be killed the task will run on the background.

public class MainActivity : Activity
{

    private int currentVolume;
    public AudioManager mAudioManager;
    private int maxVolume;
    private bool isDestory;

    Android.Media.MediaPlayer player;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        player = Android.Media.MediaPlayer.Create(this, Resource.Raw.SampleAudio);
        SetContentView (Resource.Layout.Main);
        mAudioManager = (AudioManager)GetSystemService(Context.AudioService);
        maxVolume = mAudioManager.GetStreamMaxVolume(Stream.Music);
        onVolumeChangeListener();
        player.Start();
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        isDestory = true;
    }

    private Task voluemChangeTask;

    public void onVolumeChangeListener()
    {
        currentVolume = mAudioManager.GetStreamVolume(Stream.Music);
        voluemChangeTask = new Task(ChangeVolume);
        voluemChangeTask.Start();
    }

    public void ChangeVolume()
    {
        while (!isDestory)
        {
            int count = 0;
            try
            {
                Thread.Sleep(20);
            }
            catch (Exception e)
            {

            }
            if (currentVolume < mAudioManager.GetStreamVolume(Stream.Music))
            {
                System.Console.WriteLine("volunm+");
                count++;
                currentVolume = mAudioManager.GetStreamVolume(Stream.Music);
                mAudioManager.SetStreamVolume(Stream.Music, currentVolume, VolumeNotificationFlags.RemoveSoundAndVibrate);
            }
            if (currentVolume > mAudioManager.GetStreamVolume(Stream.Music))
            {
                System.Console.WriteLine("volunm-");
                count++;
                currentVolume = mAudioManager.GetStreamVolume(Stream.Music);
                mAudioManager.SetStreamVolume(Stream.Music, currentVolume, VolumeNotificationFlags.RemoveSoundAndVibrate);
            }
        }
    }
}

I have tested it in the real device with screen lock and got the log:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM