Xamarin Android 监听音量键(下)
上篇在 MainActivity 中重写了按键事件(OnKeyDown),获取了音量键键值并打印了出来,当然,手机物理按键和虚拟按键(音量键、返回键、菜单键等)均可通过该按键事件被捕获。
但是,按键重写在 MainActivity 中,音量键按下时执行的方法在其他页面中。
作者冒出了一个不成熟的想法:利用(publish-subscribe)模式,在 MainActivity 中定义发布者(publish),实例化后层层传递到达 我的页面中,,再将实例化后的订阅者(subscribe)连接上。如图从左到右依次为类实例化的顺序:
方案实现:
1、发布者订阅者类设计
namespace NetworkAssistant { //声明按键事件监听委托接口 public delegate void OnKeyDown_callback(int keyCode); //按键事件发布者 public class MyKeyEventPublish { private int KeyCode; public Action<int> OnKeyDown { set; get; } public int OnKeyDownChanged { get { return KeyCode; } set { KeyCode = value; OnKeyDown?.Invoke(value); } } } //按键事件订阅者 public class MyKeyEventSubscribe { OnKeyDown_callback cb; public MyKeyEventSubscribe(OnKeyDown_callback _cb) { cb = _cb; } public void OnKeyDown( int newKeyCode) { Console.WriteLine($"[{newKeyCode}]"); cb?.Invoke(newKeyCode); } } }
2、MainActivity.cs
//按键事件发布者 MyKeyEventPublish myKeyEventPublish; protected override void OnCreate(Bundle savedInstanceState) { //实例化按键事件发布者 myKeyEventPublish = new MyKeyEventPublish(); TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; 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) { //键值更改事件发布方法 myKeyEventPublish.OnKeyDown((int)keyCode); //switch (keyCode) //{ // case Keycode.VolumeUp: // Message.ShortAlert("音量上"); // break; // case Keycode.VolumeDown: // Message.ShortAlert("音量下"); // break; // default:break; //} return true;//屏蔽按键原有功能 //return base.OnKeyDown(keyCode, e);//不屏蔽原有功能 }
3、App.cs
namespace NetworkAssistant { public partial class App : Application { public App(MyKeyEventPublish myKeyEventPublish) { InitializeComponent(); MainPage = new MainPage(myKeyEventPublish); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
4、MainPage.cs
//按键事件发布者 MyKeyEventPublish myKeyEventPublish; //按键事件接收者 MyKeyEventSubscribe myKeyEventSubscribe; public MainPage(MyKeyEventPublish mkp) { //实例化按键事件发布者 myKeyEventPublish = mkp; //实例化按键事件接收者 myKeyEventSubscribe = new MyKeyEventSubscribe(OnKeyDownCallBack); //增加订阅 myKeyEventPublish.OnKeyDown += myKeyEventSubscribe.OnKeyDown; InitializeComponent(); } void OnKeyDownCallBack(int keyCode) {
if (keyCode == 24) {//音量键上 //Message.ShortAlert("音量键上"); SendData("VU"); } else if (keyCode == 25) {//音量键下 //Message.ShortAlert("音量键下"); SendData("VD"); } Console.WriteLine("按键按下:"+keyCode); }
欢迎讨论,非常感谢