Pavan Vora
Pavan Vora

Reputation: 1744

How to listen for volume up/down key in android with nativescript?

I just want to know how to access volume up and down key in native script.

Upvotes: 0

Views: 1975

Answers (2)

Nick Iliev
Nick Iliev

Reputation: 9670

To do that in NativeScript you can use the code provided by James and extend the main activity for your Android NativeScript application. Below I am going to describe the steps needed to achieve that functionality with TypeScript project.

The whole demo application demonstrating the technique can be found here. Article section on how to extend the Android Activity in NativeScript can be found here (both TypeScript and vanilla JavaScript example).

Upvotes: 2

James Poulose
James Poulose

Reputation: 3833

I don't know the power button thing you are trying to do, but to handle key press events, you can try overriding dispatchKeyEvent

In short you handle the event and process KeyCode and Action - something like this

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    // Which direction did the key move (up/down)
    int action = event.getAction();

    // What keywas pressed
    int keyCode = event.getKeyCode();

    switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_UP:
            // Check your event code (KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP etc)
            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
                // Check your event code (KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP etc)
            return true;
        default:
            // Let the system do what it wanted to do
            return super.dispatchKeyEvent(event);
    }
}

Here is the full list of KeyEvent options. hope this will get you going. There is a very short description about despatchKeyEvent here

Upvotes: 1

Related Questions