其他分享
首页 > 其他分享> > Android--jni打怪第一篇

Android--jni打怪第一篇

作者:互联网

学习下 jni 开发。

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

1.新建一个jni工程

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

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

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} )

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

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

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

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 。

标签:lib,--,library,libraries,打怪,add,cpp,Android,native
来源: https://blog.csdn.net/weixin_44021334/article/details/118638374