Skip to content

Android NDK Makefile相关示例

Android.mkApplication.mk

Android Studio 3之前,需要编写Android.mkApplication.mk文件。

使用jdk8或jdk7中提供的javah来生成头文件。

build.gradle设定jni

以下是某模块的build.gradle文件

android {
    // ....
    sourceSets.main {
        jni.srcDirs = [] // 禁止自动执行ndk-build
        jniLibs.srcDirs = ['src/main/libs'] // 设定成so文件生成的目录
    }
}

指定模块的名字

Android.mk文件中指定模块的名字

LOCAL_MODULE := modname

编译得到libmodname.so文件

加载库文件

    static {
        System.loadLibrary("modname");
    }

利用$(TARGET_ARCH_ABI)判断目标架构类别

Android Studio 3之前,需要编写Android.mkApplication.mk文件。使用jdk8或jdk7。

一个典型Application.mk

APP_ABI := arm64-v8a armeabi-v7a
APP_PLATFORM := android-19
APP_STL := gnustl_static
APP_CPPFLAGS += -std=c++11

指定了2种架构

Android.mk中,可以用$(TARGET_ARCH_ABI)判断目标架构类别; 例如jni目录中有如下的文件

jni
|-- Android.mk
|-- Application.mk
|-- something.cpp
|-- include
|   |-- something.h
|-- lib
|   |-- arm64-v8a
|   |   `-- libcustom.a
|   `-- armeabi-v7a
|       `-- libcustom.a

Android.mk中判断当前编译的目标架构而加载库文件libcustom.a

LOCAL_LDFLAGS := $(LOCAL_PATH)/lib/$(TARGET_ARCH_ABI)/libcustom.a

引用OpenCV模块

假设已经下载好opencv-3.2.0SDK,Android.mk中引用

OPENCVROOT:=$(LOCAL_PATH)/../../../../../opencv-3.2.0-android-sdk/OpenCV-android-sdk
OPENCV_CAMERA_MODULES:=off
OPENCV_INSTALL_MODULES:=on
OPENCV_LIB_TYPE:=STATIC

include ${OPENCVROOT}/sdk/native/jni/OpenCV.mk

使用相对路径找到sdk,引入OpenCV的mk文件

Android NDK 通用 makefile 与相关配置

Android.mk

LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := waveExtract
TARGET_ARCH_ABI := all

LOCAL_SRC_FILES := src/wave_display.c src/FFT.c

LOCAL_LDLIBS+= -L$(SYSROOT)/usr/lib -llog

include $(BUILD_SHARED_LIBRARY)

Application.mk

APP_PLATFORM := android-19
APP_MODULES := waveExtract
APP_ABI := armeabi-v7a arm64-v8a
APP_STL := stlport_static
APP_CPPFLAGS += -fexceptions
# for using c++ features,you need to enable these in your Makefile
APP_CPP_FEATURES += exceptions rtti

build.gradle

apply plugin: 'com.android.library'

android {
    compileSdkVersion 28

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main {
            jni.srcDirs = []
            jniLibs.srcDirs = ['src/main/libs']
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:28.+'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}