[SOLVED] App to listen to the phone’s volume buttons’ events

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under
CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.


I need to create an app to listen to the phone’s volume buttons’ events. As far as I could find and test, a simple page with javascript doesn’t trigger those events, using something like this: window.addEventListener('keydown', keyDownHandler)Does making it a PWA change anything? The requirement is only for Android. Triggering when the app is closed or when the phone is locked is a big plus.

The easiest alternative I think can do the job is React Native. Is it right?


There’re multiple platforms to archive this and the easiest way I think fit you is:

1- Ionic:

It’s based on cordova and it’s the closet platform to PWA that you already using and you can handle volume buttons using this library from here.


window.addEventListener("volumebuttonslistener", onVolumeButtonsListener, false);
    function onVolumeButtonsListener(info){
        console.log("Button pressed: " + info.signal);

2- React Native

This will give you the best performance and you can handle volume buttons using this library from here.


import VolumeControl, {
} from "react-native-volume-control";


You can check if the app closed or gone to background using AppState like this example:

import {AppState} from 'react-native';

useEffect(() => {
    AppState.addEventListener('change', handleAppStateChange);
    // remove subscription
    return AppState.removeEventListener('change', handleAppStateChange);
}, []);

const handleAppStateChange = (nextAppState) => {
   // closed
   if (nextAppState === 'inactive') {
   console.log('the app is closed');
  }   else if (nextAppState === 'background') {
     console.log('the app on background');

Answered By – Louay Sleman

people found this article helpful. What about you?

Exit mobile version