Flutter plugin for detecting all hardware buttons

Overview

DEPRECATED

This plugin is deprecated :( We're no longer able to maintain it.

hardware_buttons

Version GitHub license

A Flutter plugin for iOS and Android for detecting various hardware buttons.

Note: This plugin is still under development, and some APIs might not be available yet. Feedback and Pull Requests are most welcome!

Screenshots

screenshots

Features

  • Detect volume buttons
  • Detect home button
  • Detect lock(power) button
  • To be added...

Android specification

  • If you subscribe to volume button events, this plugin will inevitably request for ACTION_MANAGER_OVERLAY_PERMISSION, since we found out this was the only way to do it well in Flutter Plugin environment. We do show permission request window for you, so there's nothing you should do other than subscribing to the event channel. However, since users may be surprised why your app needs this permission, we suggest notifying users beforehand why this permission will be requested.
  • Migrated to AndroidX as of version 1.0.0. To use with original support libraries, use version 0.2.4. Note, however, pre-AndroidX will no longer be supported.

iOS specification

  • No VOLUME_DOWN events are emitted when the volume is already at its minimum. VOLUME_UP events vice versa. On the other hand, events always occur whenever user presses the button on Android.

Usage

Import the package

To use this plugin, follow the plugin installation instructions.

To use with AndroidX, install the latest version as above instructions. To use with original support libraries, install version 0.2.4 instead.

Use the plugin

Add the following import to your Dart code:

import 'package:hardware_buttons/hardware_buttons.dart';

In order to listen to volume button events, use volumeButtonEvents.listen as below:

StreamSubscription _volumeButtonSubscription;

@override
void initState() {
  super.initState();
  _volumeButtonSubscription = volumeButtonEvents.listen((VolumeButtonEvent event) {
    // do something
    // event is either VolumeButtonEvent.VOLUME_UP or VolumeButtonEvent.VOLUME_DOWN
  });
}

@override
void dispose() {
  super.dispose();
  // be sure to cancel on dispose
  _volumeButtonSubscription?.cancel();
}

Besides volume button events, there are also:

  1. Home button events, via homeButtonEvents.listen.
  2. Lock button events, via lockButtonEvents.listen.

Example

Find the example wiring in the example app.

API details

See the hardware_buttons.dart for more API details.

Issues and feedback

Please file issues to send feedback or report a bug. Thank you!

Comments
  • Not detect event volume

    Not detect event volume

    Hi,

    On iPhone 6s plus, there is no event volume up and volume down.

    hardware_buttons: ^0.2.2

    void initState() { super.initState(); _volumeButtonSubscription = volumeButtonEvents.listen((VolumeButtonEvent event) { print(event); setState(() { hasClickVolumeDown = VolumeButtonEvent.VOLUME_DOWN == event; hasClickVolumeDown = VolumeButtonEvent.VOLUME_UP == event; }); }); }

    opened by nexussmart 9
  • 락버튼(안드로이드) / 사일런트 버튼(iOS) 구현

    락버튼(안드로이드) / 사일런트 버튼(iOS) 구현

    안드로이드는 일단 락버튼을 감지할 수 있는걸로 아는데, 갓진님이 알아본 바로 iOS에서는 막혀있다고 한다. 안드로이드도 조사는 해 봐야 한다. 락버튼을 오래 누르면 락이 되는게아니고 전원 끄기/다시 시작 이런 메뉴가 뜨는데 이런걸 분기태울수 있는지.. 분기를 태우긴 해야하는지를 고민해봐야 한다.

    iOS는 어짜피 락버튼을 할 수 없기 때문에 그 시간에 silent 버튼 감지를 구현할 수 있는지 알아보고, 가능하다면 이걸 진행!

    todo 
    opened by giantsol 9
  • 10월 6일 오프라인 회의

    10월 6일 오프라인 회의

    1. 안드로이드
    • 권한 요청 루트 점검
    • 테스트
    1. ios
    • 버전 테스트
    • mute일때 볼륨 down 눌러도 DOWN 뜨도록
    1. 공통
    • https://flutter.dev/docs/development/packages-and-plugins/developing-packages
    • 이거 보면서 필요 문서 작성 및 배포
    opened by giantsol 4
  • Kotlin Migration

    Kotlin Migration

    Hi,

    Do you have the opportunity to upgrade the version of kotlin ?

    The Android Gradle plugin supports only Kotlin Gradle plugin version 1.3.0 and higher. The following dependencies do not satisfy the required version: project ':hardware_buttons' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71

    opened by nexussmart 3
  • Use on background service

    Use on background service

    Hello, Is it possible to access hardware buttons on headless? I'm getting null error on activity, found this issue on another repository which I believe is related:

    https://github.com/transistorsoft/flutter_background_fetch/issues/11#issuecomment-462892194

    opened by dgalizzi 2
  • Installation Problem

    Installation Problem

    Hi,

    When i run my project, I get the following errors

       /....../flutter/.pub-cache/hosted/pub.dartlang.org/hardware_buttons-0.2.1/ios/Classes/VolumeButtenStreamHandler.swift:43:61: error: 'UIApplicationDidBecomeActive' has been renamed to 'UIApplication.didBecomeActiveNotification'
               notificationCenter.removeObserver(Notification.Name.UIApplicationDidBecomeActive)
                                                                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                                                   UIApplication.didBecomeActiveNotification
       UIKit.NSNotification.Name:11:23: note: 'UIApplicationDidBecomeActive' was obsoleted in Swift 4.2
           public static let UIApplicationDidBecomeActive: NSNotification.Name
                             ^
       /....../flutter/.pub-cache/hosted/pub.dartlang.org/hardware_buttons-0.2.1/ios/Classes/VolumeButtenStreamHandler.swift:49:42: error: 'AVAudioSessionCategoryAmbient' has been renamed to 'AVAudioSession.Category.ambient'
                   try audioSession.setCategory(AVAudioSessionCategoryAmbient)
                                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                                AVAudioSession.Category.ambient
       AVFoundation.AVAudioSessionCategoryAmbient:3:12: note: 'AVAudioSessionCategoryAmbient' was obsoleted in Swift 3
       public let AVAudioSessionCategoryAmbient: AVAudioSession.Category
    

    Do you have an idea ?

    Thanks

    opened by nexussmart 2
  • [ios] lock button detection timing issue

    [ios] lock button detection timing issue

    Description of the issue

    Lock button plugin can't detect immediately. It's detecting when the app returns from background to foreground.

    Users who use the plugin will expect Immediate detection. (like a home button action)

    Do you plan to provide this feature in the future?

    If you don't support it, I think you should write the README about this timing issue.

    Thanks.

    documentation question 
    opened by yenoss 2
  • 안드로이드 memory leak 이슈

    안드로이드 memory leak 이슈

    음.. 하다보니까 안드로이드에서 작업할 때 EventChannel.StreamHandler 인터페이스를 override 해서 onListen 함수에서 버튼 감지 이벤트 듣기 시작하고 onCancel 함수에서 듣던거 캔슬하는데, 앱이 종료되어도 onCancel 함수가 안불리는 버그가 있나봐여. 그래서 앱을 꺼도 버튼 감지 이벤트 캔슬이 안되어서 플러터 앱은 종료되었는데 자꾸 메시지 보내려고하니까 "W/FlutterJNI: Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: flutter.moum.hardware_buttons.volume. Response ID: 0" 요론 메시지가 계속 올라가네요.

    이런 버그가 있어서 battery 라는 플러그인에서도 이거 회피하려고하는 풀리퀘를 진행중인듯.

    위 풀리퀘보고 좀 따라해서 회피해야할듯. 결국은 플러터팀에서 onCancel 함수가 제대로 불리도록 수정해 줘야겠지만!

    iOS는 이런 버그가 없을수도 있지만 혹여나 앱을 종료했을 때 위와 같은 에러 메시지 안뜨나 확인해보심 좋을듯여~

    나중을 위해 적어둠!

    bug todo 
    opened by giantsol 2
  • [Requirement] AndroidX migration.

    [Requirement] AndroidX migration.

    Hi~ Thank you for developing this plugin!

    But I can't use your plugin because it is not migrated to AndroidX.

    I got this error.

    > Configure project :hardware_buttons
    WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'.
    It will be removed at the end of 2019.
    For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
    To determine what is calling variant.getJavaCompile(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.
             *********************************************************
    WARNING: This version of device_info will break your Android build if it or its dependencies aren't compatible with AndroidX.
             See https://goo.gl/CP92wY for more information on the problem and how to fix it.
             This warning prints for all Android build failures. The real root cause of the error may be unrelated.
             *********************************************************
      Command: /Users/yusong-i/development/PassionIndicator/android/gradlew app:properties
    
    Finished with error: Please review your Gradle project setup in the android/ folder.
    
    opened by songyiYu 1
  • [Android] 볼륨 업/다운 감지하는 로직에 의해 앱이 키보드를 못띄우는 현상

    [Android] 볼륨 업/다운 감지하는 로직에 의해 앱이 키보드를 못띄우는 현상

    지금 안드로이드에서 딱히 방법이 없어서 꼼수로 보이지 않는 윈도우 뷰를 새로 만들어서 거기서 KeyEvent를 처리하도록 했는데요, 그러다보니 앱에서 키보드가 안나오는 버그가 있습니다 ㅋㅋㅋ 이 사람도 문제 자체는 다르지만 비슷하게 윈도우 뷰를 쓰는 방식을 한게 있는데, 아래 댓글로 "Brilliant! Thanks. One problem here is that soft keyboard cant be opened :(" 라고 하네요 ㅎ.ㅎ....

    윈도우 뷰를 띄우지말고 다른 방식을 찾아봐야하나 해서 삽질을 꽤 많이 해봤는데 지금까지 알기로는 그냥 윈도우 뷰를 계속 쓰는게 나은거같고. 일단 삽질 결과 해결 방법은 찾은거같아서 풀리퀘 올릴게요.

    하.. 근데 애초에 보이지않는 윈도우 뷰를 만든다는거 자체가 뭔가 불안하네요 ㅋㅋㅋㅋㅋ

    bug 
    opened by giantsol 1
  • Android: volumeButtonEvents 구현

    Android: volumeButtonEvents 구현

    머지컨플릭을 최대한 피하기위해서 지금 단계에서는 HansolExample.dart, HardwareButtonsHansol.dart 식으로 파일을 아예 따로 만들었어요. main.dart 파일을 직접 많이 수정해버리면 어진씨가 수정한거랑 겹쳐서 머지컨플릭이 엄청 많이 날거라 ㅋ.ㅋ.. 일단 EventChannel.StreamHandler가 잘 동작하는지 확인하기위해 더미 데이터로 시험해봤습니닷

    opened by giantsol 1
  • This plugin is deprecated :( We're no longer able to maintain it

    This plugin is deprecated :( We're no longer able to maintain it

    This is one of the down-sides to flutters plugin system.

    Each plugin we depend on becomes a new liability. We now need all those plugin developers to keep up with the breaking changes pushed by google.

    opened by 3SCadmin 1
  • I am building an app that would act as a remote for presentations. I would like to use the volume buttons to trigger some sort of event. Can I capture hardware button clicks in flutter?

    I am building an app that would act as a remote for presentations. I would like to use the volume buttons to trigger some sort of event. Can I capture hardware button clicks in flutter?

    I am building an app that would act as a remote for presentations. I would like to use the volume buttons to trigger some sort of event. Can I capture hardware button clicks in flutter?

    opened by rupamking1 0
  • No detecta el Evento del Botón Bloqueo/Encendido

    No detecta el Evento del Botón Bloqueo/Encendido

    Realice las pruebas en 3 dispositivos físicos Samsung y Huawei(P9 Lite y Y9), solo funciono con el dispositivo de la marca Samsung, con los otros dispositivos no detecta el evento del Botón Bloqueo/Encendido.

    opened by Elmarcinho 0
  • Execution failed for task ':hardware_buttons:compileDebugKotlin'. > Compilation error. See log for more details

    Execution failed for task ':hardware_buttons:compileDebugKotlin'. > Compilation error. See log for more details

    After adding this to my code it does not work anymore.

    `import 'package:hardware_buttons/hardware_buttons.dart'; StreamSubscription _volumeButtonSubscription; //Volume button

    @override void initState() { super.initState(); _volumeButtonSubscription = volumeButtonEvents.listen((VolumeButtonEvent event) { if (event == VolumeButtonEvent.VOLUME_UP) { minViewer += 5; maxViewer += 5; } else if (event == VolumeButtonEvent.VOLUME_DOWN && minViewer >= 6) { minViewer -= 5; maxViewer -= 5; } }); }

    @override void dispose() { super.dispose(); _volumeButtonSubscription?.cancel(); } `

    Full Error:

    `Launching lib\main.dart on M2007J20CG in debug mode... Running Gradle task 'assembleDebug'... e: D:\Development\flutter.pub-cache\hosted\pub.dartlang.org\hardware_buttons-1.0.0\android\src\main\kotlin\flutter\moum\hardware_buttons\EmptyActivityLifecycleCallbacks.kt: (8, 6): Class 'EmptyActivityLifecycleCallbacks' is not abstract and does not implement abstract member public abstract fun onActivityPaused(@NonNull p0: Activity): Unit defined in android.app.Application.ActivityLifecycleCallbacks e: D:\Development\flutter.pub-cache\hosted\pub.dartlang.org\hardware_buttons-1.0.0\android\src\main\kotlin\flutter\moum\hardware_buttons\EmptyActivityLifecycleCallbacks.kt: (9, 5): 'onActivityPaused' overrides nothing e: D:\Development\flutter.pub-cache\hosted\pub.dartlang.org\hardware_buttons-1.0.0\android\src\main\kotlin\flutter\moum\hardware_buttons\EmptyActivityLifecycleCallbacks.kt: (11, 5): 'onActivityResumed' overrides nothing e: D:\Development\flutter.pub-cache\hosted\pub.dartlang.org\hardware_buttons-1.0.0\android\src\main\kotlin\flutter\moum\hardware_buttons\EmptyActivityLifecycleCallbacks.kt: (13, 5): 'onActivityStarted' overrides nothing e: D:\Development\flutter.pub-cache\hosted\pub.dartlang.org\hardware_buttons-1.0.0\android\src\main\kotlin\flutter\moum\hardware_buttons\EmptyActivityLifecycleCallbacks.kt: (15, 5): 'onActivityDestroyed' overrides nothing e: D:\Development\flutter.pub-cache\hosted\pub.dartlang.org\hardware_buttons-1.0.0\android\src\main\kotlin\flutter\moum\hardware_buttons\EmptyActivityLifecycleCallbacks.kt: (17, 5): 'onActivitySaveInstanceState' overrides nothing e: D:\Development\flutter.pub-cache\hosted\pub.dartlang.org\hardware_buttons-1.0.0\android\src\main\kotlin\flutter\moum\hardware_buttons\EmptyActivityLifecycleCallbacks.kt: (19, 5): 'onActivityStopped' overrides nothing e: D:\Development\flutter.pub-cache\hosted\pub.dartlang.org\hardware_buttons-1.0.0\android\src\main\kotlin\flutter\moum\hardware_buttons\EmptyActivityLifecycleCallbacks.kt: (21, 5): 'onActivityCreated' overrides nothing e: D:\Development\flutter.pub-cache\hosted\pub.dartlang.org\hardware_buttons-1.0.0\android\src\main\kotlin\flutter\moum\hardware_buttons\HardwareButtonsWatcherManager.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

    FAILURE: Build failed with an exception.

    • What went wrong: Execution failed for task ':hardware_buttons:compileDebugKotlin'.

    Compilation error. See log for more details

    • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

    • Get more help at https://help.gradle.org

    BUILD FAILED in 11s Exception: Gradle task assembleDebug failed with exit code 1 `

    opened by TimoZuerner 6
  • Detect volume raising and falling edge

    Detect volume raising and falling edge

    would it be possible to emit an single event when volume button goes from not pressed to pressed (raising edge) and the way round (when a button goes from pressed to not pressed)? I am developing a stopwatch timer and it is important to catch the raising and fallinge edges.

    opened by avafab 0
  • Listen for multiple button presses

    Listen for multiple button presses

    Hi, this isn't really an issue but I was wondering if there was a way to listen for multiple button presses?

    e.g. Home + Lock button ..

    When I try to do this (to take a screenshot on iOS) their is no recognition of either button being pressed.

    Many thanks

    opened by carman247 0
Owner
Flutter Moum
Flutter Moum
The ROHD Verification Framework is a hardware verification framework built upon ROHD for building testbenches.

ROHD Verification Framework The ROHD Verification Framework (ROHD-VF) is a verification framework built upon the Rapid Open Hardware Development (ROHD

Intel Corporation 18 Dec 20, 2022
Tasawq App — Flutter framework and Firebase An application that objectives to display all nearby stores of all kinds and real estate.

Tasawq App — Flutter framework and Firebase An application that objectives to display all nearby stores of all kinds and real estate. Multi-vendor, standard user login to view nearby products and stores for rating, follow-up, messaging and more

null 1 Nov 10, 2022
Find The Latest trending and upcoming movies and tv shows with MovieDB app. The app contains all info about movies and tv shows. find similar movies or shows, Browse all genres, video trailers, backdrops, logos, and posters.

MovieDB App Features. Dynamic Theming Search Functionality Onboarding-Screen Select favourite movie Home Screen Tranding movie Movies different catego

Ansh rathod 80 Dec 12, 2022
Flutter-sorted-chips-row - Flutter library for rendering a row of Material "Chip" buttons that gets sorted according to the given function

sorted_chips_row A Flutter Widget displaying a row of Material Chips, sorted according to the provided comparison function. How to use Adding dependen

Callstack Incubator 29 Jul 29, 2021
Implements GTK Widgets, themes and titlebar buttons in Flutter. Based on the GNOME HIG

GTK ❤️ Flutter Unofficial implementation of GTK Widgets, themes and titlebar buttons in Flutter. Based on the GNOME Human Interface Guidelines. Featur

Prateek SU 164 Dec 26, 2022
A cross-platform Flutter widget for displaying websites. Optional navigation buttons.

Overview Gives you a cross-platform Flutter widget for displaying websites and other web content. Licensed under the Apache License 2.0. Links Github

Dint 11 Oct 23, 2022
Flutter widget to create a group of buttons fast

Flutter widget to create a group of buttons fast ?? Included Radio and CheckBox

NodeMov 1 Dec 28, 2021
Example of floating buttons using dialogs on Flutter

Flutter example using floating buttons and dialogs This is a simple example showing floating buttons above a UI. These a shown via the showDialog() fu

Shamil Jamion 1 Mar 13, 2020
A Flutter package for generating sign in buttons for different social media accounts.

Sign In Button A Flutter plugin for generating sign in buttons for different social media accounts. Getting Started You must add the library as a depe

null 42 Dec 8, 2022
Flutter widget that arrange buttons in a grid.

flutter_grid_button Flutter widget that arrange buttons in a grid. It is useful for making a number pad, calculator, and so on. Getting Started To use

zuvola 11 Jan 10, 2022
A set of Flutter widgets that makes grouping Checkboxes and Radio Buttons much easier!

grouped_buttons A set of Flutter widgets that makes grouping Checkboxes and Radio Buttons much easier! Installing Add the following to your pubspec.ya

Akshath Jain 102 Dec 28, 2022
Flutter widget library containing buttons for authenticating with popular social networks: Apple, Google, Facebook, Twitter and Microsoft.

Flutter Auth Buttons This library is now in maintenance mode I'm no longer actively using Flutter and don't have the time to keep this library maintai

Duncan Jones 115 Nov 3, 2022
A Flutter package for simple and easy to use actions like buttons, checkboxes and switches.

Easy Actions Overview A Flutter package for simple and easy to use actions like buttons, checkboxes and switches. Features Elevated Button Outlined Bu

Ashish Bhakhand 3 Jun 25, 2022
Liquify your buttons, web demo at website

Hi, Introducing Liquid Button for Flutter. It supports Web and Mobile, not tested on Ios. Inspired by Liquid Button in JS. Preview Live Demo Download

Sahdeep Singh 18 Oct 31, 2021
A control pad with a virtual joystick and buttons.

control_pad A virtual pad with joystick controller and configurable buttons. Features Joystick controller Pad's buttons Configurable events interval C

Artur Rymarz 39 Dec 7, 2022
OrderFoody - A template with command buttons in horizontal scrolling list

order_coffee In this project you create a template with command buttons in horiz

Le Gia Huy 3 Jun 22, 2022
Neha Tanwar 4 Feb 2, 2022
A flutter plugin to show Truecaller like overlay window, over all other apps along with callback events

A flutter plugin to show Truecaller like overlay window, over all other apps along with callback events. Android Go or Android 11 & above, this plugin shows notification bubble, in other android versions, it shows an overlay window.

Venkata Sai Vamsi Penupothu 85 Dec 29, 2022
Awesome Notifications add-on plugin to enable push notifications through Firebase Cloud Messaging with all awesome notifications features.

Awesome Notifications FCM Awesome Notifications add-on to send push notifications using FCM (Firebase Cloud Messaging), with all awesome notifications

Rafael Setragni 8 Jan 4, 2023