Android C#:在后台服务中按下音量按钮

时间:2017-02-09 10:30:58

标签: c# android xamarin

我在C#Xamarin中创建了一个Android应用程序。

有没有办法去"听"当应用程序进入"背景"模式,即用户"锁定"他们的电话?

我已经创建了几个服务对象,并使他们成为#34;常驻"发出命令' StartCommandResult.Sticky'。

非常感谢任何C#Xamarin代码示例。

1 个答案:

答案 0 :(得分:0)

您无需创建后台服务,只需启动另一项任务即可收听音量控制。如果应用程序没有被杀死,则任务将在后台运行。

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);
            }
        }
    }
}

我已经在屏幕锁定的真实设备中对其进行了测试并得到了日志:

enter image description here