我是JNI编程的新手。我想在JNI中执行sensorEvent 解析工作,以浮点数组格式获取 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
}
答案 0 :(得分: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;
}