• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Android JNI 开发展示

武飞扬头像
Sinyu1012
帮助2

JNI 简介

JNI 是一种框架,它提供了一组接口,这些接口帮助 Java 代码调用其他语言写的代码,如 C, C 等。这种方式对于那些需要在 Java 中使用高性能或者底层系统调用的应用程序尤其有用。

学新通

JNI 在 Android 中的应用

在 Android 平台上,JNI 主要用于实现以下目标:

  1. 利用 C/C 来进行一些底层的操作,如直接访问硬件、系统等。
  2. 将一些资源密集型的操作放在更低的层级上执行,以获得更好的性能。
  3. 实现一些复杂的算法或者数学运算,如图像处理、加密解密、科学计算等。
  4. 与在 C/C 中已经存在的、优秀的库或者框架进行交互。

创建 JNI

让我们来看一个简单的例子,演示如何使用 JNI 在 Android 中调用 C 的函数。

  1. 创建一个新的 Android 项目,然后在你的 app 模块中创建一个新的 jni 文件夹。
  2. 在你的 app 模块的 build.gradle 文件中,添加以下代码:
android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }

    buildTypes {
        ...
    }

    externalNativeBuild {
        cmake {
            path "src/main/jni/CMakeLists.txt"
        }
    }
}
  1. jni 文件夹中,创建一个名为 CMakeLists.txt 的文件,并添加以下代码:
cmake_minimum_required(VERSION 3.4.1)

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             native-lib.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because system libraries are included in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )
  1. 添加 c 与 相关 代码

注意,需要保证 C 中的函数签名与 Java 中 native 函数的声明完全一致,否则会在运行时遇到找不到函数的错误。

结论

使用 JNI 在 Android 中调用 C 函数可以使我们在应用开发中更好的利用 C 的特性和性能。当然,JNI 不是一个万能的解决方案,它也会带来一些问题,如复杂度增加、调试困难等。因此,在决定使用 JNI 时,你需要仔细考虑你的应用的需求和环境。在很多情况下,使用 Java 或者 Kotlin 就已经足够了,但如果你确实需要在 Android 中使用 C ,那么 JNI 是一个非常有效的桥梁。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgiieij
系列文章
更多 icon
同类精品
更多 icon
继续加载