android JNI 开发之第一个 JNI 实例

本文旨在一步一步记录一个 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 头文件,如:

注意:

  1. 一定要进入项目根目录,然后再使用 javah 命令,否则会报 “找不到 ‘JniMethod’ 的类文件” 的错误,如下图:

  1. 使用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 文件。

ndk-build

可以看到会在与 jni 目录同级的目录下生成包含不同平台的 .so 文件的 libs 目录和 obj 目录,然后将 libs 目录中的内容复制到 Android 工程的 libs 目录中,运行程序即可。

经过如上六个步骤,一个简单的 JNI demo 程序就写好了,不过里面还包含了许多的知识点需要学习,如 Makefile 文件的内容是什么意思,该怎么写, C++ 代码如何实现等等。

常见错误

  1. 用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’

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flybirding10011

谢谢支持啊999

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值