public class MainActivity extends AppCompatActivity {
static {
System.loadLibrary("native-lib");
}
public native String stringFromJNI();//静态注册
public native String sayHello(int age);//动态注册
public void msg(final String msg){//被jni调用方法
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, msg , Toast.LENGTH_LONG).show();
}
});
}
}
#include <jni.h>
#include <string>
static void outMsg(JNIEnv *env, jobject thiz, const char *msg);
//静态注册
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_jnigetvideoaudio_MainActivity_stringFromJNI(
JNIEnv *env,
jobject thiz) {
std::string hello = "Hello from C++";
outMsg(env, thiz, hello.c_str());
return env->NewStringUTF(hello.c_str());
}
//动态注册方法
static jstring sayHello(JNIEnv *env, jobject thiz, int num) {
char name[200] = "jason liyihang";
sprintf(name, "%s---%i", name, num);
outMsg(env, thiz, name);
return env->NewStringUTF(name);
}
//动态注册函数指针列表
static JNINativeMethod javaMethods[] = {
{"sayHello", "(I)Ljava/lang/String;", (void *) sayHello}
};
//System.loadLibrary("native-lib"); 调用是出发这个方法
jint JNI_OnLoad(JavaVM *vm, void *unused) {
JNIEnv *env = NULL;
//获取环境结构体
if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
//对应java类 .换/
const char *className = "com/example/jnigetvideoaudio/MainActivity";
int methodNum = sizeof(javaMethods) / sizeof(JNINativeMethod);
jclass clazz = env->FindClass(className);
if (clazz == NULL) {
return -1;
}
//动态注册方法
int ret = env->RegisterNatives(clazz, javaMethods, methodNum);
if (ret < 0) {
env->DeleteLocalRef(clazz);
return -1;
}
//释放变量
env->DeleteLocalRef(clazz);
return JNI_VERSION_1_6;
}
//c调用java方法
static void outMsg(JNIEnv *env, jobject thiz, const char *msg) {
jclass clazz = env->GetObjectClass(thiz);
jmethodID mid = env->GetMethodID(clazz, "msg", "(Ljava/lang/String;)V");
jstring outString = env->NewStringUTF(msg);
env->CallVoidMethod(thiz, mid, outString);
env->DeleteLocalRef(clazz);
}
jni1.png
jni2.png
网友评论