主要須要配置的就是NDK(Native Development Kit),如今Android studio很便利,能夠一鍵下載:
file → setting → 按截圖找到以下路徑 → 選擇NDK → 肯定應用下載java
NDK安裝android
新建一個app,測試jni開發c++
android.useDeprecatedNdk=true
ndk.dir=NDK的路徑
apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "25.0.0" defaultConfig { applicationId "com.lilei.testjni" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" ndk { moduleName "JNISample" } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8' testCompile 'junit:junit:4.12' }
package com.lilei.testjni; /** * Created by lilei on 2017/3/29. */ public class JniUtils { public static native String getJniString(); }
cd app/build/intermediates/classes/debug/ javah com.lilei.testjni.JniUtils
運行成功以後打開app/build/intermediates/classes/debug/ 便可找到編譯出的頭文件"com_lilei_testjni_JniUtils.h",不難發現頭文件名是有原報名+類名組成app
#include "com_lilei_testjni_JniUtils.h" JNIEXPORT jstring JNICALL Java_com_lilei_testjni_JniUtils_getJniString (JNIEnv *env, jclass) { // new 一個字符串,返回Hello World return env -> NewStringUTF("Hello World"); }
static { System.loadLibrary("JNISample"); }
加載soide
package com.lilei.testjni; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i("Jni", JniUtils.getJniString()); } }
至此就成功運行出jni的Hello World了函數
前文介紹如何運行C++程序,可是實際開發中大可能是封裝編譯出so文件後進行開發,就相似java裏面的jar包工具
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := JNISample LOCAL_SRC_FILES := com_lilei_testjni_JniUtils.cpp include $(BUILD_SHARED_LIBRARY)
APP_STL := gnustl_static APP_CPPFLAGS := -frtti -fexceptions -std=c++0x APP_ABI := armeabi-v7a APP_PLATFORM := android-18
ndk-build
運行無誤的話會如圖所示測試
ndk-buildgradle
運行成功以後即會看到main文件夾下多了libs和obj的文件夾,裏面就是生成的各類CPU的so文件ui
libs和obj裏面都有so文件,二者的區別google給出的解釋是:
As part of the build process, the files in the libs folder have been stripped of symbols and debugging information. So you'll want to keep two copies of each of your .so files: One from the libs folder to install on the Android device, and one from the obj folder to install for GDB to get symbols from.
也就是說,libs目錄下生成的庫是剝離了符號表與調試信息的,而obj下的庫是帶有調試信息的。
至此jni的開發入門已完成