JNI_OnLoad ()注册函数使用方法

/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "Slmo1811"

#include "jni.h"
#include "JNIHelp.h"
#include "android_runtime/AndroidRuntime.h"

#include
#include
#include
#include

#include     
     
namespace android{


  /*在硬件抽象层中定义的硬件访问结构体,参考*/
 struct slmo1811_device_t* slmo1811_device = NULL;


  /*通过硬件抽象层定义的硬件访问接口读取硬件寄存器val 的值*/
  static jint slmo1811_getVal(JNIEnv* env, jobject clazz) {
   int val = 0;
   if(!slmo1811_device) {
    LOGI("slmo1811 JNI: device is not open.");
    return val;
   }
   slmo1811_device->get_val(slmo1811_device, &val);

   LOGI("Hello JNI: get value %d from device.", val);

   return val;
  }

 /*通过硬件抽象层定义的硬件模块打开接口打开硬件设备*/
  static inline int slmo1811_device_open(const hw_module_t* module, struct slmo1811_device_t** device) {
   return module->methods->open(module, SLMO1811_HARDWARE_MODULE_ID, (struct hw_device_t**)device);
  }


 /*通过硬件模块ID 来加载指定的硬件抽象层模块并打开硬件*/
 static jboolean slmo1811_init(JNIEnv* env, jclass clazz) {
  slmo1811_module_t* module;
  int ret=0;
  LOGI("slmo1811 JNI: initializing......");
  ret=hw_get_module(SLMO1811_HARDWARE_MODULE_ID, (const struct hw_module_t**)&module);
  LOGI("slmo1811 JNI: ret=%d",ret);
  if(ret== 0) {
   LOGI("SLMO1811 JNI: slmo1811 Stub found.");
   if(slmo1811_device_open(&(module->common), &slmo1811_device) == 0) {
    LOGI("slmo1811 JNI: slmo1811 device is open.");
    return 0;
   }
   LOGE("slmo1811 JNI: failed to open slmo1811 device.");
   return -1;
  }
  LOGE("slmo1811 JNI: failed to get slmo1811 stub module.");
  return -1;
  }


 /*JNI 方法表*/
 static  JNINativeMethod method_table[] = {
  {"init_native", "()Z", (void*)slmo1811_init},
  {"getVal_native", "()I", (void*)slmo1811_getVal},
  };

 /*注册JNI 方法*/
  int register_android_server_Slmo1811Service(JNIEnv *env) {
   return jniRegisterNativeMethods(env, "com/slmo/gpio/SlmoService", method_table, NELEM(method_table));
  }

 

/*通过System.loadLibrary("生成的so库");就可以加载OnLoad()*/

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)
    {
        LOGE("GetEnv failed!");
        return result;
    }

    register_android_server_Slmo1811Service(env);

    return JNI_VERSION_1_4;
}

};

 

你可能感兴趣的:(JNI_OnLoad ()注册函数使用方法)