Android NDK JNI 入門筆記-day01-建立項目並運行

Android NDK JNI 入門筆記目錄 java

Android Studio 3.6.1

建立項目

1. 選擇一個項目模板

Native C++

Select a Project Template

2. 配置咱們的項目

Name
Package name
Save location
Language
Minimum SDK

Configure your project

3. Customize C++ Support

C++ Standard

Customize C++ Support

4. 查看第一個 NDK-JNI 項目

查看第一個 NDK-JNI 項目

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.ihubin.ndkjni"
        ......
    }

    buildTypes {
        ......
    }

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

dependencies {
    ......
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)

add_library(
             native-lib
             SHARED
             native-lib.cpp )

find_library(
              log-lib
              log )

target_link_libraries(
                       native-lib
                       ${log-lib} )

native-lib.cpp

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

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

MainActivity.java

package com.ihubin.ndkjni;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    static {
        System.loadLibrary("native-lib");
    }

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

        TextView tv = findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }

    public native String stringFromJNI();
}

運行項目

運行項目

修改 C++ 代碼,從新運行
#include <jni.h>
#include <string>

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

從新運行項目

能夠看到,咱們修改的 C++ 代碼已經生效了。android

查看 APK

查看項目生成的 APK

至此,咱們已經學會了在 Android 項目中使用 C++ 代碼。git


代碼:github

NDKJNIday01app

參考資料:ide

Android Developers NDK 指南gradle

相關文章
相關標籤/搜索