天天看點

HelloJNI——建立NDK工程(NDK r10d)

平台

安裝配置不再贅述

  • Android NDK r10d
  • Eclipse Kelper
  • Android SDK

step1 Create a New Android project

建立一個新的android application project

step2 Add Native Support

工程右鍵,android tools–>add native support

HelloJNI——建立NDK工程(NDK r10d)

工程中就自動生成jni檔案夾并生成和工程名相同的對應cpp檔案以及makefile檔案

HelloJNI——建立NDK工程(NDK r10d)

step3 Build Project

一般工程都是build automatically

檢查CDT Build Console中,可以看到build過程

:: **** Build of configuration Default for project TestJNI ****
"F:\\android-ndk-r10d\\ndk-build.cmd" all 
Android NDK: WARNING: APP_PLATFORM android- is larger than android:minSdkVersion  in ./AndroidManifest.xml    
[armeabi] Compile++ thumb: TestJNI <= TestJNI.cpp
[armeabi] StaticLibrary  : libstdc++.a
[armeabi] SharedLibrary  : libTestJNI.so
[armeabi] Install        : libTestJNI.so => libs/armeabi/libTestJNI.so
:: Build Finished (took sms)
           

step4 Open up the Activity class

根據以下需求在activity中添加

step5 Add a function which we will implement natively in C++

即在android activity裡建立和c++檔案互動的功能函數

比如定義原生方法,從JNI裡的C++檔案擷取String

public native String  stringFromJNICPP();
……
public void onCreate(Bundle savedInstanceState){
……
        TextView myTextField = (TextView)findViewById(R.id.myTextField);
        myTextField.setText(stringFromJNICPP());  
}
           

step6 Load the native library

在acitivity裡需要加載生成的動态連接配接庫

static {
        System.loadLibrary("TestJNI");//前面自己定義的libs裡生成的so檔案名
}
           

step7 Add the native C++ code

開始寫c++檔案裡的功能

原始的c++檔案中隻有一句

在後面加上自己要寫的内容

比如傳回一個“Hello From CPP”String

#include <jni.h>
#include <string.h>
#include <android/log.h>
extern "C" {
     JNIEXPORT jstring JNICALL Java_com_example_testjni_TestJNI_stringFromJNICPP(JNIEnv * env, jobject obj);
 };//com_example_testjni_TestJNI為自己的包名裡對應的activity名
 JNIEXPORT jstring JNICALL Java_com_example_testjni_TestJNI_stringFromJNICPP(JNIEnv * env, jobject obj)
 {
     return env->NewStringUTF("Hello From CPP");
 }
           

step8 build&run

在project裡選擇Build Project,并且開啟一個虛拟機run以下建立的ndk工程

既可以在activity裡顯示從c++檔案傳送過來的string資料

HelloJNI——建立NDK工程(NDK r10d)