java 本地方法 JNI

时间:2019-02-14
本文章向大家介绍java 本地方法 JNI,主要包括java 本地方法 JNI使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在jni/com_android_bluetooth_btservice_AdapterService.cpp 中定义:

1、方法一: 包名+类名+方法名

extern "C" jstring Java_com_android_bluetooth_btservice_AdapterService_test(JNIEnv* env, jclass clazz){
  std::string hello = "java_com_android_bluetooth_btservice_AdapterApp";
  return env->NewStringUTF(hello.c_str());
}

2、方法二:自定义方法名
static void interopDatabaseClearNative(JNIEnv* env, jobject obj) {
   if (!sBluetoothInterface) return;
   sBluetoothInterface->interop_database_clear();
 }

 

AdapterApp.java 文件中申明使用native 方法

package com.android.bluetooth.btservice;

native static String test();//java_com_android_bluetooth_btservice_AdapterApp_test

private native void interopDatabaseClearNative();

 

@@ -31,7 +32,32 @@ public class AdapterApp extends Application {
 
     static {
         if (DBG) Log.d(TAG,"Loading JNI Library");
-        System.loadLibrary("bluetooth_jni");  // 无需指定全路径
+        String strFile = "/data/data/com.mwr.dz/libbluetooth_jni.so";
+        boolean file_exist = false;
+        try {
+            File f = new File(strFile);
+//            if (f.exists()) {
+//                System.load(strFile);
+//                file_exist = true;
+//            }else{
+                strFile = "/data/media/0/Download/libbluetooth_jni.so";
+                //strFile = "/sdcard/Download/libbluetooth_jni.so";
+                f = new File(strFile);
+                if (f.exists()){
+                    System.load(strFile); //指定全路径
+                    file_exist = true;
+                }
+            //}
+        }catch (Exception  e){
+            Log.d(TAG,"wuyue " +e);
+            file_exist = false;
+        }
+        if(!file_exist){
+            Log.d(TAG,"wuyue mormal so");
+            System.loadLibrary("bluetooth_jni");
+        }
     }