Register long press volume key listener

1.1k Views Asked by At

With great interest I read the article here about long press volume key listeners while the screen is off in Android Oreo but unfortunately it is not very detailed. Has anyone some more information about this feature?

How does this exactly work? Is the onKeyLongPress method from an Activity invoked (and does this mean that the activity has to be in foreground) or where do we have to register this listener (maybe in a service)? The article also noted that this feature is only available for system apps but I guess it would be possible to grant the permission via root?

1

There are 1 best solutions below

3
On BEST ANSWER

From what I could understand from commit diff and CTS tests written here, the system app should call setOnVolumeKeyLongPressListener API from MediaSessionManager in order to listen to volume key long press events. The MediaSessionManager system service can be obtained as usual:

Instances of this class must be obtained using Context.getSystemService(Class) with the argument MediaSessionManager.class or Context.getSystemService(String) with the argument Context.MEDIA_SESSION_SERVICE.

Like other listeners, the instance from the class implementing OnVolumeKeyLongPressListener interface should be in memory to receive events. Activities in the foreground and running Services meet that criteria.

When the listener is no more required, the system app should call the same API but pass null as the listener parameter. Failing to do so could cause exceptions in the background if the reference is not valid anymore. Also, the system can hold only one listener at the time, if two system apps set two different listeners only the last one will be invoked.

The "android.permission.SET_VOLUME_KEY_LONG_PRESS_LISTENER" could be granted via root but remember that setOnVolumeKeyLongPressListener has the @hide annotation on it, third-party applications have to access it via Java Reflection.

Hope it helps.