2017-02-09 50 views
0

我正在C#Xamarin中創建一個Android應用程序。Android C#:收聽後臺服務中的音量按鈕

當應用程序進入「背景」模式,即用戶「鎖定」他們的手機時,有沒有一種方法可以「收聽」音量增大/減小按鍵?

我創建了幾個Service對象,並通過發出命令「StartCommandResult.Sticky」使它們「駐留」。

任何示例C#Xamarin代碼將不勝感激。

回答

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