如何在颤动中忽略电源和音量按钮?

How to override power and volume buttons in flutter?(如何在颤动中忽略电源和音量按钮?)

本文介绍了如何在颤动中忽略电源和音量按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望覆盖电源或音量按钮,并为其提供自定义功能。我尝试了硬件按钮包(https://pub.dev/packages/hardware_buttons/example),但构建失败,并显示以下错误: C:flutter.pub-cachehostedpub.dartlang.orghardware_buttons-1.0.0androidsrcmainkotlinfluttermoumhardware_buttonsHardwareButtonsWatcherManager.kt: (74, 42): Object is not abstract and does not implement abstract base class member public abstract fun onActivityStarted(@NonNull p0: Activity): Unit defined in flutter.moum.hardware_buttons.EmptyActivityLifecycleCallbacks 在颤动中收听电源/音量按钮按下事件的最佳方式是什么?

推荐答案

我也遇到过这个问题,并使用MethodChannel和平台特定的代码解决了它。

例如,在Android端,我这样做是为了调用我的颤动代码:

class MainActivity: FlutterActivity() {
    private lateinit var channel : MethodChannel;

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "mychannel")
    }

    // using platform-specific events
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_DOWN -> channel.invokeMethod("volumeBtnPressed", "volume_down")
            KeyEvent.KEYCODE_VOLUME_UP -> channel.invokeMethod("volumeBtnPressed", "volume_up")
        }
        // return true means "prevent default behavior", so volume doesn't change and volume bar doesn't appear
        return true
    }
}

在扑翼方面(在State类中):

  static const _volumeBtnChannel =
      MethodChannel("mychannel");

  @override
  void initState() {
    _volumeBtnChannel.setMethodCallHandler((call) {
      if (call.method == "volumeBtnPressed") {
        if (call.arguments == "volume_down") {
          doMyCustomLogic();
        }
      }

      return Future.value(null);
    });
    super.initState();
  }

备注 另外,@Kozubi提到here那个快捷方式类可以以某种方式使用,但我不明白如何使用。

这篇关于如何在颤动中忽略电源和音量按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在颤动中忽略电源和音量按钮?

基础教程推荐