android JNI 开发之第一个 JNI 实例_flybirding1001的博客-程序员秘密

本文旨在一步一步记录一个 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’

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/cpongo1/article/details/102472780

智能推荐

CentOS 7安装MySql_weixin_34061482的博客-程序员秘密

为什么80%的码农都做不了架构师?&gt;&gt;&gt; ...

中点Bresenham算法光栅化画直线(个人总结精简版)代码超短!速度极快!_闲云阁的博客-程序员秘密

中点Bresenham算法光栅化画直线,每次只位移一个像素,精度高!此源码借助直线 y=x 做了一些转换,简化了主位移的处理,每次移动只需要 加减操作, 不需要乘除!速度极快!! 原理在最后,下面先贴上核心代码~void Bresenham_LineTo(CDC *pDC, int x1, int y1, int x2, int y2) //中点Bresenham算法光栅化画直线{ flo

Mahout系列之----共轭梯度预处理_weixin_30780221的博客-程序员秘密

对于大型矩阵,预处理是很重要的.常用的预处理方法有: (1) 雅克比预处理 (2)块状雅克比预处理 (3)半LU 分解 (4)超松弛法 转载于:https://www.cnblogs...

单链表来记录学生成绩信息_Amisty的博客-程序员秘密

#include &amp;lt;iostream&amp;gt;using namespace std;  const int M=100;  struct Node  {          int data;          Node *next;  };class LinkList              {      public:          LinkList();          Link...

SQL 增加列、修改列、删除列_db2 sql命令加列_xiyuan1999的博客-程序员秘密

SQL语句增加列、修改列、删除列 1.增加列: alter table tableName add columnName varchar(30)2.1. 修改列类型:alter table tableName alter column colu

我理解的逻辑地址、线性地址(虚拟地址)和物理地址_gdt中式虚拟内存地址吗_IceArmour的博客-程序员秘密

转自:http://bbs.chinaunix.net/thread-2083672-1-1.html一、概念物理地址(physical address)用于内存芯片级的单元寻址,与处理器和CPU连接的地址总线相对应。——这个概念应该是这几个概念中最好理解的一个,但是值得一提的是,虽然可以直接把物理地址理解成插在机器上那根内存本身,把内存看成一个从0字节一直到最大空量逐字节的编

随便推点

Spring中HttpInvoker远程方法调用使用实例_iteye_11495的博客-程序员秘密

代码结构图如下:客户端通过Spring的HttpInvoker,完成对远程函数的调用。涉及的类有:客户端调用User类的服务UserService,完成对实现类UserServiceImpl的addUser(User u)方法调用。其中User类为普通Pojo对象,UserService为接口,UserServiceImpl为UserService的具体实现。代码如下:publ...

nginx页面加载不全或提示502bad gateway,nginx反向代理端口号丢失_nginx 页面加载不全的问题_wh1511995112的博客-程序员秘密

Nginx反向代理模式下出现页面加载不全,或直接出现502 bad gateway的情况。出现502 bad gateway的情况有很多,大多是一些nginx相关timeout的设置问题。下文讨论一种比较少见但又不得不注意的情况。出现环境nginx工作在反向代理模式下,监听非80端口(这点很重要,监听非80端口往往意味着用户准备配置多个虚拟主机,但不限于此情境),以ip形式访问(应该在域名访问的情

从零集成腾讯广告SDK_ios 集成腾讯的开屏 告_T_TX的博客-程序员秘密

这里写自定义目录标题从零集成腾讯广告SDK话不多说直接干:功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入从零集成腾讯广告SDK话不多说直接干:在我们工程的podfile里新增pod 'GDTMobSDK'在我们的

大数据Hive(二):Hive的三种安装模式和MySQL搭配使用_hive内嵌和mysql模式_Lansonli的博客-程序员秘密

全网最详细的Hive文章系列,强烈建议收藏加关注!后面更新文章都会列出历史文章目录,帮助大家回顾知识重点。目录历史文章前言Hive的三种安装模式和MySQL搭配使用一、Hive的安装方式1、内嵌模式2、本地模式3、远程模式二、Hive的安装1、准备工作2、安装mysql数据库3、安装Hive三、Hive的交互方式第一种交互方式:bin/hive第二种交互方式:使用sql语句或者sql脚本进行交互第三种交互方式:Beeline Clien.

APP价格标签页设计灵感!多款案例选择!_awayaya1的博客-程序员秘密

价格标签仅仅是店铺标签的一部分,只能对店铺搜索起到一部分影响,而真正起到影响的则是由消费者的人群特征,消费标签等等加起来综合起到的效果。在不同类目中,价格标签对于个性化搜索权重的影响也是不同的,在竞争激烈的大类目、非标品类目而言,权重会高一些;而对于一些冷门的、小的类目,则权重影响相对较低。价格标签里不止有价格信息,不同内容的层级区分,图标等的内容传达也同样重要。集设网 www.ijishe.com 设计师交流社区带来12个联系页面的设计案例希望能给你设计灵感。更多建议:设计没思路的时候

推荐文章

热门文章

相关标签