Android 动态注册JNI

往android移植boa后,需要用java启动boa service。就要用到JNI的东西。
以前没有搞过这类东西。今天搞了一个早上,终于ok了,以下是本地实现的动态注册工作:

C代码:

#include "jni.h"
#include "JNIHelp.h"

static void
android_boa_start(
        JNIEnv *env, jobject thiz, jstring locale)
{
    initBoaService();
}

static void
android_boa_stop(
        JNIEnv *env, jobject thiz, jstring locale)
{
    destroyBoaService();
}

static JNINativeMethod gMethods[] = {
    {
        "startBoaService",
        "()V",
        (void *)android_boa_start
    },

    {
        "stopBoaService",
        "()V",
        (void *)android_boa_stop
    },

};

// This function only registers the native methods, and is called from
// JNI_OnLoad in android_media_MediaPlayer.cpp
int register_android_boa(JNIEnv *env)
{
    jclass clazz;
    static const char* const kClassName =  "com/android/jni_second/JNI";

    /* look up the class */
    clazz = (*env)->FindClass(env,kClassBoa);
    //clazz = env->FindClass(env,kClassBoa);
    if (clazz == NULL) {
        LOGE("Can't find class %s\n", kClassBoa);
        return -1;
    }

    /* register all the methods */
    if ((*env)->RegisterNatives(env,clazz, gMethods, sizeof(gMethods) / sizeof(gMethods[0])) != JNI_OK)
    //if (env->RegisterNatives(env,clazz, gMethods, sizeof(gMethods) / sizeof(gMethods[0])) != JNI_OK)
    {
        LOGE("Failed registering methods for %s\n", kClassName);
        return -1;
    }

    /* fill out the rest of the ID cache */
    return 0;
}

jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    JNIEnv* env = NULL;
    jint result = -1;

    if ((*vm)->GetEnv(vm,(void**) &env, JNI_VERSION_1_4) != JNI_OK) {
    //if (vm->GetEnv(vm,(void**) &env, JNI_VERSION_1_4) != JNI_OK) {
        LOGE("ERROR: GetEnv failed\n");
        goto bail;
    }
    assert(env != NULL);
    if (register_android_boa(env) < 0) {
        LOGE("ERROR: Boa Server native registration failed");
        goto bail;
    }

    /* success -- return valid version number */
    result = JNI_VERSION_1_4;

bail:
    return result;
}

编译后,终于可以通过了。
特别注意:代码中的红色部分。如果你的代码是C++的,那么就是红色部分调用。如果是C,红色部分编译就会出错。
具体可以查看android源代码中jni.h的定义
development/boa-0.94.13/src/android_boaService.c:292: error: request for member 'FindClass' in something not a structure or union
development/boa-0.94.13/src/android_boaService.c:300: error: request for member 'RegisterNatives' in something not a structure or union
development/boa-0.94.13/src/android_boaService.c: In function 'JNI_OnLoad':
development/boa-0.94.13/src/android_boaService.c:315: error: request for member 'GetEnv' in something not a structure or union
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值