1 FFmpeg4Android:AS中使用NDK
1.1 用Android.mk編譯.so
step 1:創(chuàng)建AS項(xiàng)目MyDNK,新建JNIS類并寫好native方法helloJNI(),如圖:

image.png
step 2: 進(jìn)入java文件夾,使用"javah com.lzp.myndk.JNIS"命令,生成頭文件:

image.png
step 3:編寫test.c文件,實(shí)現(xiàn)helloJNI()函數(shù):

image.png
step 4:修改build.gradle文件:
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
android {
...
//(1)指定動(dòng)態(tài)庫(kù)路徑
sourceSets{
main{
jni.srcDirs = [] // disable automatic ndk-build call, which ignore our Android.mk
jniLibs.srcDir 'src/main/libs'
}
}
// (2)call regular ndk-build(.cmd) script from app directory
task ndkBuild(type: Exec) {
workingDir file('src/main')
commandLine getNdkBuildCmd()
//commandLine 'E:/Android/android-ndk-r10e/ndk-build.cmd' //也可以直接使用絕對(duì)路徑
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
task cleanNative(type: Exec) {
workingDir file('src/main')
commandLine getNdkBuildCmd(), 'clean'
}
clean.dependsOn cleanNative
}
//根據(jù)不同系統(tǒng)獲取ndk-build腳本
def getNdkBuildCmd() {
def ndkbuild = getNdkDir() + "/ndk-build"
if (Os.isFamily(Os.FAMILY_WINDOWS))
ndkbuild += ".cmd"
return ndkbuild
}
//獲取NDK目錄路徑
def getNdkDir() {
if (System.env.ANDROID_NDK_ROOT != null)
return System.env.ANDROID_NDK_ROOT
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkdir = properties.getProperty('ndk.dir', null)
if (ndkdir == null)
throw new GradleException("NDK location not found. Define location with ndk.dir in the local.properties file or with an ANDROID_NDK_ROOT environment variable.")
return ndkdir
}
...
step 6:編譯.so文件,有兩種方式:
(1)使用ndk-build命令:
進(jìn)入app\src\main,在cmd中執(zhí)行NDK的ndk-build命令生成動(dòng)態(tài)庫(kù)(ndk-build所在文件夾,即NDK目錄如果沒有加入環(huán)境變量則需要絕對(duì)路徑);
(2)使用編譯腳本(推薦):
編寫Android.mk和Application.mk
Android.mk:
# Android.mk
# walker lee
# http://blog.csdn.net/itismelzp
LOCAL_PATH := $(call my-dir)
# Program
include $(CLEAR_VARS)
LOCAL_MODULE := jni-native # 庫(kù)文件,對(duì)應(yīng)生成libjni-native.so文件
LOCAL_SRC_FILES :=test.c # 還可添加其他.c文件
LOCAL_C_INCLUDES += $(LOCAL_PATH)/include
LOCAL_LDLIBS := -llog -lz
include $(BUILD_SHARED_LIBRARY)
Application.mk:
APP_ABI :=armeabi
APP_PLATFORM := android-9
點(diǎn)擊工具欄中的build->Make Project,會(huì)在main目錄下生成兩個(gè)目錄libs和obj,動(dòng)態(tài)庫(kù)便在其中:

image.png
1.2 用CMakeList編譯.so
step 1:新建CMakeLists.txt文件:
# Sets the minimum version of CMake required to build the native
# library. You should either keep the default value or only pass a
# value of 3.4.0 or lower.
cmake_minimum_required(VERSION 3.4.1)
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 )
add_library( jni-native
SHARED
src/main/jni/test.c )
include_directories(jni)
#target_include_directories(jni-native PRIVATE jni)
target_link_libraries( jni-native
${log-lib} )