将android的代码移动到本机代码

时间:2017-12-01 09:00:26

标签: java android java-native-interface native

我是jni的新手,我正在尝试开发支持本机代码的Android应用程序。目前我正在尝试将用于访问电池温度的代码从java层移动到本地代码。

java代码是:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.getBaseContext().registerReceiver(null, ifilter);
int temperature = batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,-1);

虽然我为原生部分写的是:

jclass intentFilterClass = (*env)->FindClass(env,"android/content/IntentFilter");
jclass intentClass = (*env)->FindClass(env,"android/content/Intent");
jclass ContextClass = (*env)->FindClass(env,"android/content/Context");
jclass ContextWrapperClass = (*env)->FindClass(env,"android/content/ContextWrapper");

jclass activityThread = (*env)->FindClass(env,"android/app/ActivityThread");
jmethodID currentActivityThread = (*env)->GetStaticMethodID(env,activityThread, "currentActivityThread", "()Landroid/app/ActivityThread;");
jobject at = (*env)->CallStaticObjectMethod(env,activityThread, currentActivityThread);

jmethodID getApplication = (*env)->GetMethodID(env,activityThread, "getApplication", "()Landroid/app/Application;");
jobject context = (*env)->CallObjectMethod(env,at, getApplication);
if (context == NULL){
    LOGE("TEST ", " context is null");  
}

jmethodID constructorIntentFilter = (*env)->GetMethodID(env,intentFilterClass,"<init>","()V");
jobject IntentFilterObject = (*env)->NewObject(env,intentFilterClass,constructorIntentFilter,"android.intent.action.BATTERY_CHANGED");
if (IntentFilterObject == NULL){
     LOGE("TEST ", "IntentFilterObject is null"); 
}

jmethodID registerReceiver = (*env)->GetMethodID(env, ContextClass,"registerReceiver","(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
if (registerReceiver == NULL){
     LOGE("TEST ", " registerreceiver is null"); 
}

jobject IntentObject = (*env)->CallObjectMethod(env,thiz,registerReceiver,NULL,IntentFilterObject);
if (IntentObject == NULL){
    LOGE("TEST ", "IntentObject is null"); 
}

jmethodID getIntExtra = (*env)->GetMethodID(env, intentClass,"getIntExtra","(Ljava/lang/String;I)I");
jint res = (*env)->CallIntMethod(env,IntentObject,getIntExtra,"temperature",-1);

不幸的是,由于访问空指针,应用程序崩溃了。事实上,IntentObject始终为null。

jobject IntentObject = (*env)->CallObjectMethod(env,thiz,registerReceiver,NULL,IntentFilterObject);

Pidcat错误日志:

 art  F  art/runtime/java_vm_ext.cc:410] JNI DETECTED ERROR IN APPLICATION: can't call int android.content.Intent.getIntExtra(java.lang.String, int) on null object

0 个答案:

没有答案