Android Framework层添加JNI方法

依据Android的Binder设计思想,有些时候在Server层需要对JNI的方法进行实现。
如在我们自定义的Java Serve中进行以下实现
./frameworks/base/services/core/java/com/android/server/LedStatusManagerService.java

package com.android.server;

import android.content.Context;
import android.util.Log;
import android.util.Slog;
import android.app.ILedStatusManager;

/**
 * @hide
 */
public class LedStatusManagerService extends ILedStatusManager.Stub{
    private static final String TAG = "LedStatusManagerService";

    private native int get_led_mode();

    private Context mContext;
    public LedStatusManagerService(Context context) {
        super();
        this.mContext=context;
    }

    /**
     * @hide
     */
    public int getLedMode(){
        System.out.println("LedStatusManagerService init to getLedMode");
        return get_led_mode();
    }
}

Java中定义了private native int get_led_mode()方法用于jni实现,接下来我们定义cpp文件
./frameworks/base/services/core/jni/com_android_server_LedStatusManagerService.cpp

#include "jni.h"
#include <utils/Log.h>
#include <android_runtime/Log.h>
#define LOG_TAG "LedStatusManagerService-JNI"

namespace android {
//定义方法的实现
static jint android_server_LedStatusManagerService_getLedMode(JNIEnv *env, jobject thiz){
    ALOGE("android_server_LedStatusManagerService_getLedMode \n",);
    return 0;
}

//jni方法映射定义
static const JNINativeMethod sMethods[] = {
    {"get_led_mode", "()I", (void*)android_server_LedStatusManagerService_getLedMode},
};

int register_android_server_LedStatusManagerService(JNIEnv* env)
{
    return jniRegisterNativeMethods(env, "com/android/server/LedStatusManagerService",//指明Java文件
                                    sMethods, NELEM(sMethods));
}
}

注册完之后我们还需要定义jni库的自动加载
./frameworks/base/services/core/jni/onload.cpp

#include "JNIHelp.h"
#include "jni.h"
#include "utils/Log.h"
#include "utils/misc.h"

namespace android {
....
//声明函数
int register_android_server_LedStatusManagerService(JNIEnv* env);
....
};

using namespace android;

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

    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
        ALOGE("GetEnv failed!");
        return result;
    }
    ALOG_ASSERT(env, "Could not retrieve the env!");
    ....
    //函数执行
    register_android_server_LedStatusManagerService(env);
    ....

    return JNI_VERSION_1_4;
}

经过上诉代码定义的函数就可以被正确加载了,但是我们还需要将我们的cpp文件一起打包进os库中在
./frameworks/base/services/core/jni/Android.mk中的 LOCAL_SRC_FILES += \ 添加我们实现的cpp文件 $(LOCAL_REL_DIR)/com_android_server_LedStatusManagerService.cpp \ 即可.

发表评论

CAPTCHAis initialing...