If I forward key event such as back button press to unity activity using dispatchKeyEvent it is not working from unity 4.5.x version on wards. Same method is working fine in unity 4.3.x.
The way I have implemented is show below. I want to keep the same implementation as I am sending some other events as well.
private const int KEY_CODE_BACK = 4;
private const int KEY_ACTION_DOWN = 0;
void Update () {
…
if (Input.GetKeyDown(KeyCode.Escape)) {
SendKeyEvent(KEY_ACTION_DOWN, KEY_CODE_BACK);
}
if(Input.GetKeyUp(KeyCode.Escape)) {
SendKeyEvent(KEY_ACTION_UP, KEY_CODE_BACK);
}
…
}
void SendKeyEvent(int action, int code) {
AndroidJavaClass cUnityPlayer = new AndroidJavaClass(“com.unity3d.player.UnityPlayer”);
AndroidJavaObject oCurrentActivity = cUnityPlayer.GetStatic(“currentActivity”);
oCurrentActivity.Call(“runOnUiThread”, new AndroidJavaRunnable(() => {
AndroidJavaObject oKeyEventDown = new AndroidJavaObject(“android.view.KeyEvent”, action, code);
oCurrentActivity.Call(“dispatchKeyEvent”, oKeyEventDown)
}
}
I have also tried sending the event to the Window of the activity. In that case calling sequence is Activity.getWindow().getCallback().dispatchKeyEvent().
But if I call onBackPressed directly using the activity object then it is working fine, but I don’t want to use in this way.