Search Unity

dispatchKeyEvent does not trigger in Unity - Native Android plugin

Discussion in 'Android' started by acylum, Nov 8, 2017.

  1. acylum

    acylum

    Joined:
    Jul 16, 2013
    Posts:
    3
    I'm trying to detect the Volume UP or Volume down button press on an Android device(allow a "selfie stick" to control the phone). I created a plugin using this tutorial.

    http://addcomponent.com/android-native-plugin-unity/

    While the function "whatsThePoint" does return a value to a Unity c# script, I can't get the dispatchKeyEvent function to trigger - when I hit the volume up/volume down buttons on the device. (I looked at Android monitor/logcat in Android Studio)

    Is there something I'm missing?
    here is my .java code

    Code (CSharp):
    1. package com.addcomponent.unitynativeplugin;
    2. import android.util.Log;
    3. import com.unity3d.player.UnityPlayer;
    4. import android.view.KeyEvent;
    5. import  android.app.Activity;
    6.  
    7. public class Examples extends  Activity{
    8.  
    9.  
    10.     public void whatsThePoint(String gameObject, String method) {
    11.        
    12.         UnityPlayer.UnitySendMessage(gameObject, method, "good.");
    13.     }
    14.    
    15.    
    16.     @Override
    17.     public boolean dispatchKeyEvent(KeyEvent event) {
    18.  
    19.         int action = event.getAction();
    20.         int keyCode = event.getKeyCode();
    21.         switch (keyCode) {
    22.             case KeyEvent.KEYCODE_VOLUME_UP:
    23.                 if (action == KeyEvent.ACTION_DOWN) {
    24.                     Log.d("test", "Volume UP pressed! " + event);
    25.                     UnityPlayer.UnitySendMessage("NativeBridge", "WhatsThePointReceived", "VOLUME up");
    26.                 }
    27.                 return true;
    28.             case KeyEvent.KEYCODE_VOLUME_DOWN:
    29.                 if (action == KeyEvent.ACTION_DOWN) {
    30.                     Log.d("test", "Volume DOWN pressed! " + event);
    31.                     UnityPlayer.UnitySendMessage("NativeBridge", "WhatsThePointReceived", "VOLUME down");
    32.                 }
    33.                 return true;
    34.             default:
    35.                 return super.dispatchKeyEvent(event);
    36.         }
    37.     }
    38. }

    Here is the C# code that receives the data from the plugin
    Code (CSharp):
    1. public void WhatsThePointReceived (string message)
    2.     {
    3.         appMessage = message+"::"+Time.fixedTime;
    4.     }