欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Android studio3.6的JNI教程之helloworld思路詳解

 更新時間:2020年03月19日 21:15:25   作者:watersink  
這篇文章主要介紹了基于Android studio3.6的JNI教程之helloworld,本文通過圖文實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

jdk環(huán)境變量配置:

path中增加下面2個路徑,也就是android studio的路徑,android有自帶的jdk。

E:\Android\Android Studio\jre\bin
E:\Android\Android Studio\bin

新建工程:

一定要選擇Native c++類型,最后要選c++11支持。

SDK設置:

File->Settings

File->Project Structure

首先確定工程的目錄結構,然后嘗試運行一下工程,使用模擬器,確保工程沒問題,

MainActivity的同級目錄,新建一個hello.java,然后做一個簡單的實現(xiàn),

package com.example.myapplication;
 
public class hello {
 public native int add(int i, int j);
}

使用android studio自帶的Terminal進入該hello.java所在目錄,執(zhí)行,

javac hello.java

Terminal下回到app/src/main所在目錄,執(zhí)行,

javah -d jni -classpath ./java com.example.myapplication.hello

此時,會在main目錄下面生成一個和cpp,java同級的目錄jni。

在該目錄結構里面新建hello.cpp。

com_example_myapplication_hello.h中的內容復制進hello.cpp中,并且進行方法的實現(xiàn),

#include <jni.h>
/* Header for class com_example_myapplication_hello */
 
#ifndef _Included_com_example_myapplication_hello
#define _Included_com_example_myapplication_hello
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class: com_example_myapplication_hello
 * Method: add
 * Signature: (II)I
 */
 
#include "com_example_myapplication_hello.h"
 
JNIEXPORT jint JNICALL Java_com_example_myapplication_hello_add
 (JNIEnv *, jobject, jint i, jint j){return i+j;}
 
#ifdef __cplusplus
}
#endif
#endif

com_example_myapplication_hello.h,hello.cpp這連個文件復制到cpp所在的目錄,

然后修改CMakeLists.txt,增加,

add_library( # Sets the name of the library.
 hello
 
 # Sets the library as a shared library.
 SHARED
 
 # Provides a relative path to your source file(s).
 hello.cpp )

修改target_link_libraries如下,

target_link_libraries( # Specifies the target library.
  native-lib
  hello
  # Links the target library to the log library
  # included in the NDK.
  ${log-lib} )

修改hello.java的調用方式,

package com.example.myapplication;
 
public class hello {
 
 static {
 System.loadLibrary("hello");
 }
 public native int add(int i, int j);
}

修改MainActivity.java中的onCreate函數(shù),

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 // Example of a call to a native method
 TextView tv = findViewById(R.id.sample_text);
 //tv.setText(stringFromJNI());
 tv.setText("hello 9+10= " + new hello().add(9, 10));
 }

然后,rebuild project,沒有錯誤后,然后run app。

最終程序整體目錄結構,以及運行效果,

 JNI的整體流程思路:

Java先定義一個類,類中定義一個需要c++來實現(xiàn)的方法.通過javah生成需要c++實現(xiàn)的.h的c++頭文件實現(xiàn).h的c++頭文件中定義的方法Cmake編譯運行

總結

到此這篇關于基于Android studio3.6的JNI教程之helloworld思路詳解的文章就介紹到這了,更多相關android studio JNI helloworld內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論