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

核能气质少年 提交于 2019-12-09 14:00:00

问题


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


回答1:


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.

  • Create new file in your app folder called activity.android.ts

  • in the newly created file extend the Activity and overwrite dispatchKeyEvent as done here in my demonstration application

  • lastly, provide the new activity to your AndroidManifest file by replacing the default one created by NativeScript

  • build the application and use volume keys - the code will be triggered as expected (in the demo application simple console.log)

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).




回答2:


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



来源:https://stackoverflow.com/questions/45943511/how-to-listen-for-volume-up-down-key-in-android-with-nativescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!