程序员

JNI应用-初步应用

2020-06-12  本文已影响0人  世外大帝

今天拉了一下3年前的ndk代码,发现和现在Android Studio生成的代码相差比较大,就重新写一个吧.

后面仍然会进一步探索,这个demo只是简单的融合生成的cpp文件和自建的cpp文件,在不同的路径下可以使用同一个库名称。

本章是否生成头文件不重要,可以应用即可。

因为本身比较简单,所以就不写注释了,如果有网友没接触过,可以留言提问。

创建项目

选择 Native C++

配置

创建对应的java文件

MyJNI.java

package com.jiataoyuan.createsodemo;

/**
 * created by Taoyuan on 2020/6/12
 */
public class MyJNI {
    static {
        System.loadLibrary("myJNI");
    }

    public native String sayHello(String context);
    public native int sum(int x, int y);

}

main下的cpp文件夹中创建cpp文件

MyJNI.cpp

//
// Created by Taoyuan on 2020/6/12.
//

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

extern "C"
JNIEXPORT jstring JNICALL
Java_com_jiataoyuan_createsodemo_MyJNI_sayHello(JNIEnv *env, jobject instance, jstring content) {
    jboolean isCopy;
    const char *temp = env->GetStringUTFChars(content, &isCopy);
    std::string say = "say Hello!\n";
    say.append(temp);
    env->ReleaseStringUTFChars(content, temp);
    return env->NewStringUTF(say.c_str());
}

extern "C" //表示对java输出
JNIEXPORT jint JNICALL
Java_com_jiataoyuan_createsodemo_MyJNI_sum(JNIEnv *env, jobject instance, jint x, jint y) {
    return x + y;
}

配置到CMakeLists.txt文件中

MyJNI.java

# 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.
        myJNI

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        native-lib.cpp
        MyJNI.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.
        myJNI

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

应用

在 MainActivity 中创建对象直接使用即可。

package com.jiataoyuan.createsodemo;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

    @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);

        MyJNI myJNI = new MyJNI();
        StringBuilder sb = new StringBuilder();
        sb
                .append(stringFromJNI())
                .append("\n")
                .append(myJNI.sayHello("this is myJNI"))
                .append("\n")
                .append(myJNI.sum(10, 20))
                .append("\n");
        tv.setText(sb);
    }

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

}

生成so文件

  1. build 或 make project
  2. 找到目录 build -> intermediates -> cmake -> release或debug -> obj
  3. 复制到 main 目录下的 jniLibs 目录中即可

如果使用so文件报错:More than one file was found with OS independent path 'lib/armeabi-v7a/libmyJNI.so',请参考:

https://blog.csdn.net/lftaoyuan/article/details/106718096

使用so文件

  1. 删掉 MyJNI.cpp 文件
  2. 在 CMakeLists.txt 文件中删掉 MyJNI.cpp
  3. 在 native-lib.cpp 文件中添加 MyJNI.h 头文件
  4. 运行即可,效果等同直接使用cpp文件
上一篇下一篇

猜你喜欢

热点阅读