JNI preliminary configuration and implementation of a small example

First configure the ndk path in local.properties in the new project

ndk.dir=C\:\\android-ndk-r10e

 Share this version of ndk here

Link: https://pan.baidu.com/s/1bL3yKwYrrpff_CuvHlNHyQ 
Extraction code: weaj 

Configure environment variables

Configure compatible old version ndk project in gradle.properties under gradle.properties 

#android.useDeprecatedNdk=true
android.deprecatedNdkCompileLease=1600525901073

How to use jni

1. First create a new class that calls c code. Here is Godv as an example

public class Godv {
    {
        System.loadLibrary("Hello");
    }
    //定义调用代码
    public native String sayHello();
}

2.build.gradle(app)android -> defaultConfig下配置

ndk{
            moduleName "Hello"  //so   文件   lib+moduleName+.so
            abiFilters 'armeabi' , 'armeabi','x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a' //cpu类型
        }
        sourceSets{
            main{
                jniLibs.srcDirs=['libs']
            }
        }

3. Write c file

#include <stdio.h>
#include <stdlib.h>
#include <jni.h>

jstring Java_com_godv_hello_Godv_sayHello (JNIEnv * env ,jobject jobj)
{
    char * text = "hello i am godv ";
    return (* env)->NewStringUTF(env,text);
}

4.main

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String s = new Godv().sayHello();
        System.out.println(s);
    }
}

 

Guess you like

Origin blog.csdn.net/we1less/article/details/108685734