在JNI中提取SensorEvent

问题描述 投票:0回答:1

我是JNI编程的新手。我想在JNI中执行sensorEvent解析作业,以获取float数组格式的sensorEvent.values。

但我不知道如何提取jobject sensorEvent来获取JNI上的sensorEvent.values?

// JAVA
public class MySensor {

    // load native dll
    static {
        System.loadLibrary("example"); 
    }

    // this native function will be call by onSensorChanged()
    private native void parse(SensorEvent sensorEvent); 

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent != null) {

            // content of sensorEvent.values is
            //   sensorEvent.values[0] = 1.0f
            //   sensorEvent.values[1] = 1.1f
            //   sensorEvent.values[1] = 1.2f               
            parse(sensorEvent);     // do this job in JNI
        }
    }

}

// JNI
JNIEXPORT void JNICALL
Java_com_company_MySensor_parse(JNIEnv *env, jobject instance, jobject sensorEvent) {

    // how to extract sensorEvent to get sensorEvent.values and show values?     
    //??? 

    printf("SensorEvent.values[0]= %f", sensorEvent.values[0]); // 1.0f
    printf("SensorEvent.values[1]= %f", sensorEvent.values[1]); // 1.1f
    printf("SensorEvent.values[2]= %f", sensorEvent.values[2]); // 1.2f
}
android android-ndk java-native-interface sensor
1个回答
0
投票

根据@Michael的信息,我找到了答案。谢谢你们。

const char *CLS_SENSOR_EVENT = "android/hardware/SensorEvent";
const char *FLD_VALUES = "values";
const char *SIG_VALUES = "[F";

jfloat getSensorValue(JNIEnv *env, jobject sensorEvent) {
    jboolean* isCopy = JNI_FALSE;

    jclass clsSensorEvent = env->FindClass(CLS_SENSOR_EVENT);
    if (NULL == clsSensorEvent) {
        return -1;
    }
    jfieldID fldValues = env->GetFieldID(clsSensorEvent, FLD_VALUES, SIG_VALUES);
    if (NULL == fldValues) {
        return -1;
    }
    jobject objValues = env->GetObjectField(sensorEvent, fldValues);
    if (NULL == objValues) {
        return -1;
    }

    jfloatArray floArrValues = reinterpret_cast<jfloatArray>(objValues);
    jfloat *flo = env->GetFloatArrayElements(floArrValues, isCopy);
    if (NULL == *flo) {
        return -1;
    }
    jfloat result = flo[0];
    env->ReleaseFloatArrayElements(floArrValues, flo, 0);
    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.