本例子有些问题不能实现,我不知道为什么?
1.JniZoo.c
#include <jni.h>
#include "stdio.h"
#include <android/log.h>
#define LOG_TAG "libJniZoo"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define HED (*env)
JNIEXPORT void JNICALL Java_com_example_jnitest01_JniZoo_callJNIInt
(JNIEnv *env, jobject thiz, int nParam)
{
jclass cls = HED->FindClass(env,"com/example/jnitest01/MainActivity");
jmethodID med = HED->GetMethodID(env,cls,"callBackInt","(I)V");
if(med == NULL)
{
LOGI("not fond med");
return;
}
else
{
LOGI("fond med");
}
LOGI(" nParam = %d",nParam);
(*env)->CallVoidMethod(env,thiz,med,nParam);
}
2. JniZoo.java
package com.example.jnitest01;
public class JniZoo {
public native static void callJNIInt(int i);
static
{
System.loadLibrary("JniZoo");
}
}
3. MainActivity.java
package com.example.jnitest01;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tvInt ,tvStr,tvByte;
Button btInt,btStr,btByte;
//JniZoo jniZ = new JniZoo();
private Handler handler = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btInt = (Button)findViewById(R.id.intbt);
btInt.setOnClickListener(new btnOnClickListener());
btStr = (Button)findViewById(R.id.strbt);
btStr.setOnClickListener(new btnOnClickListener());
btByte = (Button)findViewById(R.id.bytebt);
btByte.setOnClickListener(new btnOnClickListener());
tvInt = (TextView)findViewById(R.id.inttv);
tvStr = (TextView)findViewById(R.id.stringtv);
tvByte = (TextView)findViewById(R.id.bytetv);
handler = new Handler()
{
public void handleMessage(Message msg)
{
switch(msg.what)
{
case 0:
tvInt.setText(msg.obj.toString());
break;
case 2:
tvStr.setText(msg.obj.toString());
break;
case 3:
byte b[] = (byte [])msg.obj;
tvByte.setText(Byte.toString(b[0])+ Byte.toString(b[1]) );
break;
}
}
};
}
public class btnOnClickListener implements OnClickListener
{
public void onClick(View v)
{
switch(v.getId())
{
case R.id.intbt:
JniZoo.callJNIInt(2);
//callJNIInt(2);
break;
case R.id.strbt:
//jniZ.callJNIStr("你好世界");
break;
case R.id.bytebt:
//jniZ.callJNIByte(new byte[]{1,2,3,4,5});
break;
}
}
}
public void callBackInt(int i)
{
Message msg = new Message();
msg.obj = i;
msg.what = 0;
handler.sendMessage(msg); // 这里的原因 handler 不会执行,如果把 JinZoo.java 中的内容写到该文件就可以,当然分开也可以,不过要再研究下
}
public void callBackStr(String s)
{
Message msg = new Message();
msg.obj = s;
msg.what = 2;
handler.sendMessage(msg);
}
public void callBackByte(Byte b[])
{
Message msg = new Message();
msg.obj = b;
msg.what = 3;
handler.sendMessage(msg);
}
}
现在的问题是,按了 intBt 按键后,界面就消失了; lib库编译没有错误, 类,方法等都可以找到;