IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android--jni打怪第一篇 -> 正文阅读

[移动开发]Android--jni打怪第一篇

学习下 jni 开发。

确保 AS 已经安装了相关的 SDK 工具,主要是 LLDB 、NDK 、CMAKE
在这里插入图片描述

1.新建一个jni工程

新建一个 jni 工程,选择 Native C++ ,
在这里插入图片描述
新建完成。

本例包名 com.cosmos.jniapplication 。

看看默认生成的工程的都有什么东西。

1.1 主页面MainActivity

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");//注释1
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());//注释2
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();//注释3
}

注释1 处,声明加载 native-lib 库。
注释3 处,声明了 native 方法。
注释2 处,调用 native 方法。

1.2 native-lib.cpp

工程路径在 JniApplication\app\src\main\cpp\native-lib.cpp 。

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring JNICALL
Java_com_cosmos_jniapplication_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

方法简单返回一个字符串。

1.3 CMakeLists.txt

自动生成的,关注 native-lib ,它是 cpp 文件的名称。

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

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 CMake includes system libraries 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} )

app 的 build.gradle 里,在 android { } 中也有对它的声明,

externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
            version "3.10.2"
        }
    }

build 运行一下,按照预计结果显示 Hello from C++ 。

解压生成的 apk ,lib 目录里有 libnative-lib.so 。

1.4 小结

参考默认的例子,小结一下,jni 开发流程是这样的(自己的理解,不对勿喷):

  • 1.写好cpp文件;
  • 2.在 CMakeLists.txt 中添加对 cpp 的声明,主要是 add_library 、 target_link_libraries ;
  • 3.在 java 中加载库、声明native方法、调用。
  • 4.生成apk,验证 lib 下有生成对应的 so 。

2.新加一个自己的方法

默认生成的例子有一个实例了。照葫芦画瓢,自己加一个方法。

2.1 在 native-lib.cpp 中添加方法

在 native-lib.cpp 中添加方法 Java_com_cosmos_jniapplication_MainActivity_getMaxNum,

四个参数,env、jobject 是 jni 语法要求的参数,a 、b 才是实际用的参数,简单返回两者最大值。

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring JNICALL
Java_com_cosmos_jniapplication_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

extern "C" JNIEXPORT jint JNICALL
Java_com_cosmos_jniapplication_MainActivity_getMaxNum(
        JNIEnv* env,
        jobject,
        jint a,
        jint b
        ){
    return a > b ? a : b;
}

2.2 声明新加的方法并使用

因为新加的方法是在 native-lib.cpp 中,声明加载 native-lib 库这一步已经完成过了。

声明新加的 native 方法并使用,

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
        System.loadLibrary("new-add");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        //tv.setText(stringFromJNI());
        tv.setText(getMaxNum(10,9));//使用
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    public native int getMaxNum(int a, int b);//声明
}

运行一下,是预期结果。说明加对了.

3.添加新的库

来,接着造。

3.1 新建cpp

在 native-lib.cpp 同级目录下新建一个 new-add.cpp 文件。

老规矩,参考默认的例子写,简单求和。

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jint JNICALL
Java_com_cosmos_jniapplication_MainActivity_getSum(
        JNIEnv *env,
        jobject,
        jint a,
        jint b) {
    return a + b;
}

3.2 CMakeLists.txt 中添加新库的声明

修改 CMakeLists.txt ,添加对新加的库的声明。

关注 # for new-add begin 注释段,名字要对应上

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

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 CMake includes system libraries 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} )
# for new-add begin
add_library( # Sets the name of the library.
        new-add

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        new-add.cpp)
target_link_libraries( # Specifies the target library.
        new-add

        # Links the target library to the log library
        # included in the NDK.
        ${log-lib} )
# for new-add end

3.3 加载、声明、使用

注释4 处声明加载 new-add 库,
注释5 处声明 new-add 库中的 native方法,
注释6 处调用方法。

package com.cosmos.jniapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
        System.loadLibrary("new-add");//注释4
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        //tv.setText(stringFromJNI());
        //tv.setText(getMaxNum(10,9));
        tv.setText(String.valueOf(getSum(10,20)));//注释6
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    public native int getMaxNum(int a, int b);

    public native int getSum(int a, int b);//注释5
}

build 运行一下,是期望结果。

解压生成的 apk ,lib 目录里有生成 libnew-add.so 。

第一篇, done 。

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-07-11 16:45:21  更:2021-07-11 16:45:28 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/20 6:05:01-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码