隐藏

Xamarin.Forms Android PDA 监听手机按键

发布:2021/10/25 11:18:34作者:管理员 来源:本站 浏览次数:1152

1.介绍
项目中,有个需求是监听手机音量按键,并在ContentPage页面进行事件处理。
2.解决方案

1.新建事件发送者
新建 MyKeyEventPublish.cs ,代码如下

public class MyKeyEventPublish
    {
        //全局静态变量,以便在需要监听时使用
        public static MyKeyEventPublish myKeyEventPublish { get; set; }

        public delegate void OnKeyDown_callback(int keyCode);
        public OnKeyDown_callback cb;

        public Action<int> OnKeyDown { set; get; }
    }


2.App.cs

 public App(MyKeyEventPublish myKeyEventPublish)
   {
       InitializeComponent();
      //监听手机按键
       MyKeyEventPublish.myKeyEventPublish = myKeyEventPublish;            
       //起始页
       MainPage = new NavigationPage(new Login());           
   }

 

3.MainActivity.cs (Android)

//按键事件发布者
MyKeyEventPublish myKeyEventPublish;
 protected override void OnCreate(Bundle savedInstanceState)
 {
     TabLayoutResource = Resource.Layout.Tabbar;
     ToolbarResource = Resource.Layout.Toolbar;
     //实例化按键发布者
     myKeyEventPublish = new MyKeyEventPublish();
     
     base.OnCreate(savedInstanceState);
     Xamarin.Essentials.Platform.Init(this, savedInstanceState);
     global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
     LoadApplication(new App(myKeyEventPublish));
 }
 //监听键盘按下
 public override bool OnKeyDown([GeneratedEnum]Keycode keyCode, KeyEvent e)
  {
       if (keyCode == Android.Views.Keycode.Back) {
           return base.OnKeyDown(keyCode,e);
       }
       if (myKeyEventPublish == null || myKeyEventPublish.OnKeyDown == null) return true;
       //键值更改事件发布方法
       myKeyEventPublish.OnKeyDown((int)keyCode);
       return true;          
       //return base.OnKeyDown(keyCode, e); //不屏蔽原有功能
   }

  

4.ContentPage.cs 页面使用

public Login()
 {
      InitializeComponent();
      NavigationPage.SetHasNavigationBar(this, false);
      this.Appearing += Login_Appearing;
      this.Disappearing += Login_Disappearing;
  }
 //页面销毁
  private void Login_Disappearing(object sender, EventArgs e)
  {
      MyKeyEventPublish.myKeyEventPublish.OnKeyDown -= OnKeyDownCallBack;
  }
  //页面显示
  private void Login_Appearing(object sender, EventArgs e)
  {
     MyKeyEventPublish.myKeyEventPublish.OnKeyDown += OnKeyDownCallBack;
  }
  //这个是处理函数
  void OnKeyDownCallBack(int keyCode)
  {
     Console.WriteLine("keycode:" + keyCode);
  }


以上是全部代码,如有问题,请及时评论!我会一一解答!请多多点赞哦!