从Java将MotionEvent发送到JNI [英] Send MotionEvent from Java to JNI

查看:106
本文介绍了从Java将MotionEvent发送到JNI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过JNI将Java中的MotionEvent发送到C ++?

Is it possible to send MotionEvent from Java to C++ through JNI?

我在C ++中有一个方法,该方法应该接收一个指向AInputEvent的指针,以将其发送到Game类:

I have a method in C++ that should receive a pointer to AInputEvent to send it to the Game class:

JNIEXPORT void JNICALL
Java_com_game_ActivityMain_onTouch(JNIEnv *jenv, jclass obj,jobject event) {
    AInputEvent* inputEvent=(AInputEvent*)event;
    game->OnInput(inputEvent);
    }
};

在Java中,我将本机方法声明为:

in Java I declared the native method as:

public static native void onTouch(MotionEvent event);

但是当我在屏幕上切换时,应用程序崩溃了.

but the application crashes when I tab on the screen.

我猜想这不可能完成,因为Java TouchEvent和JNI AInputEnvent不是同一类型.那我该怎么办?

I guess this can't be done since Java TouchEvent and JNI AInputEnvent is not the same type. so what should I do?

我在JNI端创建了一个结构,并通过调用方法填充了它的字段,这是最好的情况吗?

Edit 2: I created a struct in JNI side and fill its fields by calling methods, is this the best scenario?

jclass eventClss=jenv->GetObjectClass(event);
jmethodID methodId = jenv->GetMethodID(eventClss, "getX", "()F");
float x = jenv->CallFloatMethod(event, methodId);

推荐答案

我理解AInputEventMotionEvent都是不同的类型,不能互相转换,因此我将MotionEvent作为jobject发送并使用JNI Environment访问其方法和字段.

I understood both AInputEvent and MotionEvent are different type and can't be cast to each other, so I send MotionEvent as jobject and accessed its method and fields using the JNI Environment.

JNIEXPORT void JNICALL
Java_com_game_ActivityMain_onTouch(JNIEnv *jenv, jclass obj,jobject motionEvent) {
    jclass motionEventClass=jenv->GetObjectClass(motionEvent);

    jmethodID pointersCountMethodId = jenv->GetMethodID(motionEventClass,"getPointerCount", "()I");
    int pointersCount = jenv->CallIntMethod(motionEvent, pointersCountMethodId);
    jmethodID getActionMethodId = jenv->GetMethodID(motionEventClass, "getAction", "()I");
    int32_t action = jenv->CallIntMethod(motionEvent, getActionMethodId);

    jmethodID getXMethodId = jenv->GetMethodID(motionEventClass, "getX", "(I)F");
    float x0 = jenv->CallFloatMethod(motionEvent, getXMethodId,0);

    jmethodID getYMethodId = jenv->GetMethodID(motionEventClass, "getY", "(I)F");
    float y0 = jenv->CallFloatMethod(motionEvent, getYMethodId,0);

    float x1=0;
    float y1=0;
    if(pointersCount>1){
        x1 = jenv->CallFloatMethod(motionEvent, getXMethodId,1);
        y1 = jenv->CallFloatMethod(motionEvent, getYMethodId,1);
    }

    States::MotionEvent inputEvent;
    inputEvent.PointersCount=pointersCount;
    inputEvent.Action=action;
    inputEvent.X0=x0;
    inputEvent.Y0=y0;
    inputEvent.X1=x1;
    inputEvent.Y1=y1;
    game->OnMotionEvent(inputEvent);
}

这篇关于从Java将MotionEvent发送到JNI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆