本文旨在一步一步記錄一個 JNI 實例的誕生過程及在這個過程中我遇到的坑 & 解決方案。作為一個以前沒有接觸過 JNI 開發的新手,以下步驟中很多內容都看不懂,所以也不打算在本文中詳細介紹,不過會在以后的博文中慢慢記錄。
Step 1
新建一個 Android 工程,我姑且將該工程命名為 FirstJni。
新建一個 Java 文件,在該文件中加載 JNI 的庫和定義需要通過 native 實現的方法,如下:
public class JniMethod {
static {
/**
* 類加載時便加載庫文件,文件名與實現所需的庫函數的 C 代碼文件名相同
*/
System.loadLibrary("JniMethod");
}
// native 方法
public static native String getNativeString(String s);
}
同時我將 MainActivity 修改如下,使得點擊 button 時,顯示通過 native 方法獲取的字符串,從而可以測試 native 方法是否成功調用。
public class MainActivity extends AppCompatActivity {
private TextView mView;
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mView = (TextView) findViewById(R.id.tv);
mButton = (Button)findViewById(R.id.btn);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mView.setText(getNativeString("Native string"));
}
});
}
}
我的項目結構如圖所示:
Step 2
進入剛剛寫的 JniMethod 所在的目錄,使用 javac 命令編譯該類,得到該類的 .class 文件,因為后面需要通過該 .class 文件生成 .h 頭文件,如:
Step 3
進入項目根目錄,使用 javah 命令生成與 JniMethod.class 文件相對應的 .h 頭文件,如:
注意:
- 一定要進入項目根目錄,然后再使用 javah 命令,否則會報 “找不到 ‘JniMethod’ 的類文件” 的錯誤,如下圖:
- 使用javah命令時,類名不能添加后綴“.class”,添加了的話會報IllegalArgumentException異常;
接下來可以在項目根目錄下看到一個頭文件,名為 “com_lilacouyang_test_JniMethod”,你可以繼續使用該名稱,但我為了簡便,重命名為“JniMethod”了。
Step 4
為了方便,新建一個 jni 目錄,保存所有與 JNI 相關的文件。將剛剛生成的 JniMethod.h 移到該目錄中,然后創建一個 JniMethod.c 的文件,實現定義在 JniMethod.h 頭文件中方法。
頭文件:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_lilacouyang_firstjni_JniMethod */
#ifndef _Included_com_lilacouyang_firstjni_JniMethod
#define _Included_com_lilacouyang_firstjni_JniMethod
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_lilacouyang_firstjni_JniMethod
* Method: getNativeString
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_lilacouyang_firstjni_JniMethod_getNativeString
(JNIEnv *, jclass, jstring);
#ifdef __cplusplus
}
#endif
#endif
c 文件示例:
/*
* 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.
*
*/
#include <string.h>
#include <jni.h>
/* This is a trivial JNI example where we use a native method
* to return a new VM String. See the corresponding Java source
* file located at:
*
* E:\Lilac-Applications\Test\app\src\main\java\com\lilacouyang\firstjni\JniMethod.java
*/
jstring
Java_com_lilacouyang_firstjni_JniMethod_getNativeString( JNIEnv* env,
jobject thiz )
{
#if defined(__arm__)
#if defined(__ARM_ARCH_7A__)
#if defined(__ARM_NEON__)
#if defined(__ARM_PCS_VFP)
#define ABI "armeabi-v7a/NEON (hard-float)"
#else
#define ABI "armeabi-v7a/NEON"
#endif
#else
#if defined(__ARM_PCS_VFP)
#define ABI "armeabi-v7a (hard-float)"
#else
#define ABI "armeabi-v7a"
#endif
#endif
#else
#define ABI "armeabi"
#endif
#elif defined(__i386__)
#define ABI "x86"
#elif defined(__x86_64__)
#define ABI "x86_64"
#elif defined(__mips64) /* mips64el-* toolchain defines __mips__ too */
#define ABI "mips64"
#elif defined(__mips__)
#define ABI "mips"
#elif defined(__aarch64__)
#define ABI "arm64-v8a"
#else
#define ABI "unknown"
#endif
return (*env)->NewStringUTF(env, "Hello from JNI ! Compiled with ABI " ABI ".");
}
Step 5
創建 Android.mk 和 application.mk 文件,即 Makefile 文件。
注意: Android.mk 和 application.mk 文件需要保存在根目錄下的jni文件夾中,不然
可能出現Android NDK: Your APP_BUILD_SCRIPT points to an unknown file
的錯誤。
Android.mk
# 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.
#
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := JniMethod
LOCAL_SRC_FILES := JniMethod.c
include $(BUILD_SHARED_LIBRARY)
Application.mk
APP_ABI := all
Step 6
進入到 Android.mk 所在的目錄,運行 ndk-build 命令,得到動態庫 .so 文件。
可以看到會在與 jni 目錄同級的目錄下生成包含不同平臺的 .so 文件的 libs 目錄和 obj 目錄,然后將 libs 目錄中的內容復制到 Android 工程的 libs 目錄中,運行程序即可。
經過如上六個步驟,一個簡單的 JNI demo 程序就寫好了,不過里面還包含了許多的知識點需要學習,如 Makefile 文件的內容是什么意思,該怎么寫, C++ 代碼如何實現等等。
常見錯誤
- 用C++編譯器編譯C語言變量
error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'
return (*env)->NewStringUTF(env, "Hello from JNI on 2018-08-29! Compiled with ABI " ABI ".");
解決方案:
1)將C++編譯器改為C語言編譯器;
2)將C變量改為C++變量,如將(*env)->NewStringUTF(env, "Hello from JNI on 2018-08-29! Compiled with ABI " ABI ".");
改為return env->NewStringUTF("Hello from JNI on 2018-08-29! Compiled with ABI " ABI ".");
參見: # error: base operand of ‘->’ has non-pointer type ‘JNIEnv’