我想從本機代碼調用java方法。我遵循的步驟如下: Calling a java method from c++ in Android從本地代碼調用java函數時出錯
但是我的應用程序崩潰在調用java函數的地方。
我的Java代碼是,如下所示:
02-14 15:37:06.814: D/MYAPP(11584): bArray successfully created...
:打印日誌消息後
#include <jni.h>
#include "com_example_jnitry_MainActivity.h"
#include <android/log.h>
#include <stdio.h>
JNIEXPORT void JNICALL Java_com_example_jnitry_MainActivity_mainfunc
(JNIEnv *env, jclass obj, jint n){
__android_log_print(ANDROID_LOG_DEBUG,"MYAPP","mainfunction entered...",NULL);
int i;
unsigned char arr[10];
jbyteArray bArray=(*env)->NewByteArray(env,n);
jclass cls = (*env)->FindClass(env, "com/example/jnitry/MainActivity");
jmethodID mid = (*env)->GetMethodID(env, cls, "display", "([B)V");
if (mid == 0){
__android_log_print(ANDROID_LOG_DEBUG,"MYAPP","mid==0",NULL);
return;
}
if(bArray==NULL)
{ __android_log_print(ANDROID_LOG_DEBUG,"MYAPP","bArray==NULL...",NULL);
return ;
}
for(i=0;i<n;i++){
arr[i]=i;
__android_log_print(ANDROID_LOG_DEBUG,"MYAPP","Iteration number:%d",i);
}
(*env)->SetByteArrayRegion(env,bArray,0,n,arr);
__android_log_print(ANDROID_LOG_DEBUG,"MYAPP","bArray successfully created...",NULL);
(*env)->CallVoidMethod(env, obj, mid, bArray);
__android_log_print(ANDROID_LOG_DEBUG,"MYAPP","Returned from disp() java function.....",NULL);
}
我的應用崩潰:如下圖所示
package com.example.jnitry;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MYAPP","Ocreate entered....");
Button btn=(Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mainfunc(8);
}
});
}
public void display(byte[] byt){
Log.d("MYAPP", "display() is entered....");
for(int i=0;i<byt.length;i++)
Log.d("MYAPP", "byt["+i+"]="+byt[i]);
Log.d("MYAPP", "display finished");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public static native void mainfunc(int n);
static
{
System.loadLibrary("mylib");
}
}
我的本機代碼任何人都可以請告訴我原因。併爲此提供解決方案。提前致謝。
注:我已經嘗試CallVoidMedthodA(),callByteMethod(),CallObjectMethod()但結果是一樣的。
非常感謝你...正如你所建議的,刪除靜態關鍵字工作.... – Zax 2013-02-15 05:07:44