java – 从jni访问加速度计

前端之家收集整理的这篇文章主要介绍了java – 从jni访问加速度计前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试制作一个 Android应用程序,我需要在jni中访问加速度计.

java代码

mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);         
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

jni代码

jclass cls_context = env->FindClass("android/content/Context");
jfieldID tService = env->GetStaticFieldID(cls_context,"SENSOR_SERVICE","Ljava/lang/String;");
jstring jstr = (jstring)env->GetStaticObjectField(cls_context,tService);

//getSystemService(SENSOR_SERVICE);
jclass cls_act = env->GetObjectClass(activity);
jmethodID GetSystemService = env->GetMethodID(cls_act,"getSystemService","(Ljava/lang/String;)Ljava/lang/Object;");
jobject systemservice = env->CallObjectMethod(activity,GetSystemService,jstr);

//getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
jclass sensormanager = env->GetObjectClass(systemservice);
jmethodID getdefaultsensor = env->GetMethodID(sensormanager,"getDefaultSensor","(I)Landroid/hardware/Sensor;");
jobject sensor = env->CallObjectMethod(systemservice,getdefaultsensor,"Sensor.TYPE__ACCELEROMETER");

但是jobject传感器变得无效.

解决方法

Sensor.TYPE_ACCELEROMETER是int类型的内联常量,值为1,应该在那里传递.

但无论如何,分成9行JNI代码的那两行看起来很糟糕.离开那些原始的Java代码然后从JNI调用它不是更好吗?

猜你在找的Java相关文章