android ndk 入门2 - 基本方法实现

2024-06-21 15:48

本文主要是介绍android ndk 入门2 - 基本方法实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 新建工程NDKTest,新建一个空Activity

新建java类MyNDK.java:

package com.zj.ndktest;/*** Created by root on 15-11-25.*/
public class MyNDK {static {System.loadLibrary("hello-jni");}public static native String Hello();
}

local.properties上加入:

sdk.dir=/opt/android-sdk-linux
ndk.dir=/opt/android-ndk-r10e

app/build.gradle上加入:

apply plugin: 'com.android.application'android {compileSdkVersion 23buildToolsVersion "23.0.2"defaultConfig {applicationId "com.zj.ndktest"minSdkVersion 15targetSdkVersion 23versionCode 1versionName "1.0"ndk { moduleName "hello-jni"}}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}
}dependencies {compile fileTree(dir: 'libs', include: ['*.jar'])testCompile 'junit:junit:4.12'compile 'com.android.support:appcompat-v7:23.1.0'
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:id="@+id/text_view"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>

MainActivity.java:

package com.zj.ndktest;import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;public class MainActivity extends Activity {private TextView mTextView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);mTextView = (TextView)findViewById(R.id.text_view);mTextView.setText(MyNDK.Hello());}
}

点击MyNDK.java文件,右键点击External Tools->javah(没有的请查看android ndk 入门 - 一个简单的ndk工程)

生成app/src/main/jni/com_zj_ndktest_MyNDK.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_zj_ndktest_MyNDK */#ifndef _Included_com_zj_ndktest_MyNDK
#define _Included_com_zj_ndktest_MyNDK
#ifdef __cplusplus
extern "C" {
#endif
/** Class:     com_zj_ndktest_MyNDK* Method:    Hello* Signature: ()Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *, jclass);#ifdef __cplusplus
}
#endif
#endif

新建jni/Android.mk:

LOCAL_PATH := ${call my-dir}
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := main.cpp
include ${BUILD_SHARED_LIBRARY}

新建main.cpp:

#include <jni.h>
#include "com_zj_ndktest_MyNDK.h"JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *env, jclass cla) {return env->NewStringUTF("Hello JNI");
}

运行,即可完成简单的ndk程序


####################################################################


实现int输入,int输出

在MyNDK.java上加入:

    public static native int HelloIntegerAdd(int a, int b);public static native int HelloIntegerSubtract(int a, int b);public static native int HelloIntegerMultiply(int a, int b);public static native int HelloIntegerDivide(int a, int b);

在activity_main.xml上加入:

    <TextViewandroid:id="@+id/text_integer_add"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_integer_subtarct"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_integer_multiply"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_integer_divide"android:layout_width="match_parent"android:layout_height="wrap_content" />

在MainActivity上加入:

package com.zj.ndktest;import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;public class MainActivity extends Activity {private TextView mTextView;private TextView mTextIntegerAdd;private TextView mTextIntegerSubtract;private TextView mTextIntegerMultiply;private TextView mTextIntegerDivide;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);mTextView = (TextView)findViewById(R.id.text_view);mTextView.setText(MyNDK.Hello());StringBuffer text_integer_add = new StringBuffer("3 + 5 =");text_integer_add.append(MyNDK.HelloIntegerAdd(3, 5));mTextIntegerAdd = (TextView)findViewById(R.id.text_integer_add);mTextIntegerAdd.setText(text_integer_add.toString());StringBuffer text_integer_subtract = new StringBuffer("33 - 100 = ");text_integer_subtract.append(MyNDK.HelloIntegerSubtract(33, 100));mTextIntegerSubtract = (TextView)findViewById(R.id.text_integer_subtarct);mTextIntegerSubtract.setText(text_integer_subtract.toString());StringBuffer text_integer_multiply = new StringBuffer("6 * 23 = ");text_integer_multiply.append(MyNDK.HelloIntegerMultiply(6, 23));mTextIntegerMultiply = (TextView)findViewById(R.id.text_integer_multiply);mTextIntegerMultiply.setText(text_integer_multiply.toString());StringBuffer text_integer_divide = new StringBuffer("90 / 32 = ");text_integer_divide.append(MyNDK.HelloIntegerDivide(90, 32));mTextIntegerDivide = (TextView)findViewById(R.id.text_integer_divide);mTextIntegerDivide.setText(text_integer_divide.toString());}
}

点击MyNDK.java,右键->External Tools->javah

生成新的com_zj_ndktest_MyNDK.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_zj_ndktest_MyNDK */#ifndef _Included_com_zj_ndktest_MyNDK
#define _Included_com_zj_ndktest_MyNDK
#ifdef __cplusplus
extern "C" {
#endif
/** Class:     com_zj_ndktest_MyNDK* Method:    Hello* Signature: ()Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *, jclass);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloIntegerAdd* Signature: (II)I*/
JNIEXPORT jint JNICALL Java_com_zj_ndktest_MyNDK_HelloIntegerAdd(JNIEnv *, jclass, jint, jint);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloIntegerSubtract* Signature: (II)I*/
JNIEXPORT jint JNICALL Java_com_zj_ndktest_MyNDK_HelloIntegerSubtract(JNIEnv *, jclass, jint, jint);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloIntegerMultiply* Signature: (II)I*/
JNIEXPORT jint JNICALL Java_com_zj_ndktest_MyNDK_HelloIntegerMultiply(JNIEnv *, jclass, jint, jint);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloIntegerDivide* Signature: (II)I*/
JNIEXPORT jint JNICALL Java_com_zj_ndktest_MyNDK_HelloIntegerDivide(JNIEnv *, jclass, jint, jint);#ifdef __cplusplus
}
#endif
#endif

main.cpp修改为:

#include <jni.h>
#include "com_zj_ndktest_MyNDK.h"JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *env, jclass cla) {return env->NewStringUTF("Hello JNI");
}/** Class:     com_zj_ndktest_MyNDK* Method:    HelloIntegerAdd* Signature: (II)I*/
JNIEXPORT jint JNICALL Java_com_zj_ndktest_MyNDK_HelloIntegerAdd(JNIEnv *env, jclass cla, jint a, jint b) {jint c;c = a + b;return c;
}/** Class:     com_zj_ndktest_MyNDK* Method:    HelloIntegerSubtract* Signature: (II)I*/
JNIEXPORT jint JNICALL Java_com_zj_ndktest_MyNDK_HelloIntegerSubtract(JNIEnv *env, jclass cla, jint a, jint b) {jint c;c = a - b;return c;
}/** Class:     com_zj_ndktest_MyNDK* Method:    HelloIntegerMultiply* Signature: (II)I*/
JNIEXPORT jint JNICALL Java_com_zj_ndktest_MyNDK_HelloIntegerMultiply(JNIEnv *env, jclass cla, jint a, jint b) {jint c;c = a * b;return c;
}/** Class:     com_zj_ndktest_MyNDK* Method:    HelloIntegerDivide* Signature: (II)I*/
JNIEXPORT jint JNICALL Java_com_zj_ndktest_MyNDK_HelloIntegerDivide(JNIEnv *env, jclass cla, jint a, jint b) {jint c;c = a / b;return c;
}

运行:



############################################################################################3


实现double输入,double输出


修改MyNDK.java如下:

package com.zj.ndktest;/*** Created by root on 15-11-25.*/
public class MyNDK {static {System.loadLibrary("hello-jni");}public static native String Hello();public static native double HelloDoubleAdd(double a, double b);public static native double HelloDoubleSubtract(double a, double b);public static native double HelloDoubleMultiply(double a, double b);public static native double HelloDoubleDivide(double a, double b);
}

修改activity_main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:id="@+id/text_view"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_double_add"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_double_subtarct"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_double_multiply"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_double_divide"android:layout_width="match_parent"android:layout_height="wrap_content" />
</LinearLayout>

修改MainActivity.java如下:

package com.zj.ndktest;import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;public class MainActivity extends Activity {private TextView mTextView;private TextView mTextDoubleAdd;private TextView mTextDoubleSubtract;private TextView mTextDoubleMultiply;private TextView mTextDoubleDivide;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);mTextView = (TextView)findViewById(R.id.text_view);mTextView.setText(MyNDK.Hello());StringBuffer text_double_add = new StringBuffer("3.0 + 5.0 =");text_double_add.append(MyNDK.HelloDoubleAdd(3.0, 5.0));mTextDoubleAdd = (TextView)findViewById(R.id.text_double_add);mTextDoubleAdd.setText(text_double_add.toString());StringBuffer text_double_subtract = new StringBuffer("33.0 - 100.0 = ");text_double_subtract.append(MyNDK.HelloDoubleSubtract(33.0, 100.0));mTextDoubleSubtract = (TextView)findViewById(R.id.text_double_subtarct);mTextDoubleSubtract.setText(text_double_subtract.toString());StringBuffer text_double_multiply = new StringBuffer("6.0 * 23.0 = ");text_double_multiply.append(MyNDK.HelloDoubleMultiply(6.0, 23.0));mTextDoubleMultiply = (TextView)findViewById(R.id.text_double_multiply);mTextDoubleMultiply.setText(text_double_multiply.toString());StringBuffer text_double_divide = new StringBuffer("90.0 / 32.0 = ");text_double_divide.append(MyNDK.HelloDoubleDivide(90.0, 32.0));mTextDoubleDivide = (TextView)findViewById(R.id.text_double_divide);mTextDoubleDivide.setText(text_double_divide.toString());}
}

点击MyNDK.java,右键->External Tools->javah,生成新的com_zj_ndktest_MyNDK.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_zj_ndktest_MyNDK */#ifndef _Included_com_zj_ndktest_MyNDK
#define _Included_com_zj_ndktest_MyNDK
#ifdef __cplusplus
extern "C" {
#endif
/** Class:     com_zj_ndktest_MyNDK* Method:    Hello* Signature: ()Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *, jclass);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleAdd* Signature: (DD)D*/
JNIEXPORT jdouble JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleAdd(JNIEnv *, jclass, jdouble, jdouble);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleSubtract* Signature: (DD)D*/
JNIEXPORT jdouble JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleSubtract(JNIEnv *, jclass, jdouble, jdouble);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleMultiply* Signature: (DD)D*/
JNIEXPORT jdouble JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleMultiply(JNIEnv *, jclass, jdouble, jdouble);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleDivide* Signature: (DD)D*/
JNIEXPORT jdouble JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleDivide(JNIEnv *, jclass, jdouble, jdouble);#ifdef __cplusplus
}
#endif
#endif

修改main.cpp如下:

#include <jni.h>
#include "com_zj_ndktest_MyNDK.h"JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *env, jclass cla) {return env->NewStringUTF("Hello JNI");
}/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleAdd* Signature: (DD)D*/
JNIEXPORT jdouble JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleAdd(JNIEnv *env, jclass cla, jdouble a, jdouble b) {jdouble c;c = a + b;return c;
}/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleSubtract* Signature: (DD)D*/
JNIEXPORT jdouble JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleSubtract(JNIEnv *env, jclass cla, jdouble a, jdouble b) {jdouble c;c = a - b;return c;
}/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleMultiply* Signature: (DD)D*/
JNIEXPORT jdouble JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleMultiply(JNIEnv *env, jclass cla, jdouble a, jdouble b) {jdouble c;c = a * b;return c;
}/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleDivide* Signature: (DD)D*/
JNIEXPORT jdouble JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleDivide(JNIEnv *env, jclass cla, jdouble a, jdouble b) {jdouble c;c = a / b;return c;
}

运行:




###################################################################


输入boolean,输出boolean


修改MyNDK.java如下:

package com.zj.ndktest;/*** Created by root on 15-11-25.*/
public class MyNDK {static {System.loadLibrary("hello-jni");}public static native String Hello();public static native boolean HelloBoolean(boolean b);
}

修改activity_main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:id="@+id/text_view"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_boolean_view"android:layout_width="match_parent"android:layout_height="wrap_content" />
</LinearLayout>

修改MainActivity.java如下:

package com.zj.ndktest;import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;public class MainActivity extends Activity {private TextView mTextView;private TextView mTextBoolean;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);mTextView = (TextView)findViewById(R.id.text_view);mTextView.setText(MyNDK.Hello());StringBuffer text_boolean = new StringBuffer("True = ");text_boolean.append(MyNDK.HelloBoolean(true));mTextBoolean = (TextView)findViewById(R.id.text_view);mTextBoolean.setText(text_boolean.toString());}
}

点击MyNDK.java,右键->External Tools->javah,生成com_zj_ndktest_MyNDK.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_zj_ndktest_MyNDK */#ifndef _Included_com_zj_ndktest_MyNDK
#define _Included_com_zj_ndktest_MyNDK
#ifdef __cplusplus
extern "C" {
#endif
/** Class:     com_zj_ndktest_MyNDK* Method:    Hello* Signature: ()Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *, jclass);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloBoolean* Signature: (Z)Z*/
JNIEXPORT jboolean JNICALL Java_com_zj_ndktest_MyNDK_HelloBoolean(JNIEnv *, jclass, jboolean);#ifdef __cplusplus
}
#endif
#endif

修改main.cpp如下:

#include <jni.h>
#include "com_zj_ndktest_MyNDK.h"JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *env, jclass cla) {return env->NewStringUTF("Hello JNI");
}JNIEXPORT jboolean JNICALL Java_com_zj_ndktest_MyNDK_HelloBoolean(JNIEnv *env, jclass cla, jboolean b) {jboolean res = JNI_FALSE;if (b == JNI_TRUE) {res = JNI_TRUE;} else {res = JNI_FALSE;}return res;
}

运行:



##################################################################################


输入jstring,double,输出jstring


修改MyNDK.java:

package com.zj.ndktest;/*** Created by root on 15-11-25.*/
public class MyNDK {static {System.loadLibrary("hello-jni");}public static native String Hello();public static native String sprint(String format, double x);
}

修改activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:id="@+id/text_view"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_string_view"android:layout_width="match_parent"android:layout_height="wrap_content" />
</LinearLayout>

修改MainActivity.java:

package com.zj.ndktest;import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;public class MainActivity extends Activity {private TextView mTextView;private TextView mTextString;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);mTextView = (TextView)findViewById(R.id.text_view);mTextView.setText(MyNDK.Hello());mTextString = (TextView)findViewById(R.id.text_string_view);mTextString.setText(MyNDK.sprint("Amount due = %8.2f", 33.4556));}
}

点击MyNDK.java,右键->External Tools->javah,生成com_zj_ndktest_MyNDK.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_zj_ndktest_MyNDK */#ifndef _Included_com_zj_ndktest_MyNDK
#define _Included_com_zj_ndktest_MyNDK
#ifdef __cplusplus
extern "C" {
#endif
/** Class:     com_zj_ndktest_MyNDK* Method:    Hello* Signature: ()Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *, jclass);/** Class:     com_zj_ndktest_MyNDK* Method:    sprint* Signature: (Ljava/lang/String;D)Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_sprint(JNIEnv *, jclass, jstring, jdouble);#ifdef __cplusplus
}
#endif
#endif

修改main.cpp如下:

#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include "com_zj_ndktest_MyNDK.h"JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *env, jclass cla) {return env->NewStringUTF("Hello JNI");
}JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_sprint(JNIEnv *env, jclass cla, jstring format, jdouble x) {const char* cformat;jstring ret;cformat = env->GetStringUTFChars(format, NULL);char *cret;cret = (char*)malloc(strlen(cformat)+8);sprintf(cret, cformat, x);ret = env->NewStringUTF(cret);free(cret);env->ReleaseStringUTFChars(format, cformat);return ret;
}

运行:




#############################################################


访问实例域


删除MyNDK.java文件,新建Employee.java文件:

package com.zj.ndktest;/*** Created by root on 15-11-25.*/
public class Employee {static {System.loadLibrary("hello-employee");}private String name;private double salary;public Employee(String n, double s) {name = n;salary = s;}public native void raiseSalary(double byPercent);public String print() {StringBuffer sb = new StringBuffer();sb.append(name);sb.append(" ");sb.append(salary);return sb.toString();}
}

修改activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:id="@+id/text_instance_view"android:layout_width="match_parent"android:layout_height="wrap_content" />
</LinearLayout>

修改MainAcitvity.java:

package com.zj.ndktest;import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;public class MainActivity extends Activity {private TextView mTextInstance;;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);Employee em = new Employee("hello world", 32000);em.raiseSalary(5);mTextInstance = (TextView)findViewById(R.id.text_instance_view);mTextInstance.setText(em.print());}
}

修改app/build.gradle:

apply plugin: 'com.android.application'android {compileSdkVersion 23buildToolsVersion "23.0.2"defaultConfig {applicationId "com.zj.ndktest"minSdkVersion 15targetSdkVersion 23versionCode 1versionName "1.0"ndk {// moduleName "hello-jni"moduleName "hello-employee"}}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}
}dependencies {compile fileTree(dir: 'libs', include: ['*.jar'])testCompile 'junit:junit:4.12'compile 'com.android.support:appcompat-v7:23.1.0'
}

点击Employee.java,右键->Extrenal Tools->javah,生成com_zj_ndktest_Employee.h:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_zj_ndktest_Employee */#ifndef _Included_com_zj_ndktest_Employee
#define _Included_com_zj_ndktest_Employee
#ifdef __cplusplus
extern "C" {
#endif
/** Class:     com_zj_ndktest_Employee* Method:    raiseSalary* Signature: (D)V*/
JNIEXPORT void JNICALL Java_com_zj_ndktest_Employee_raiseSalary(JNIEnv *, jobject, jdouble);#ifdef __cplusplus
}
#endif
#endif

修改Android.mk:

LOCAL_PATH := ${call my-dir}
include $(CLEAR_VARS)
LOCAL_MODULE := hello-employee
LOCAL_SRC_FILES := main.cpp
include ${BUILD_SHARED_LIBRARY}

修改main.cpp:

#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include "com_zj_ndktest_Employee.h"JNIEXPORT void JNICALL Java_com_zj_ndktest_Employee_raiseSalary(JNIEnv *env, jobject obj, jdouble byPercent) {/* get the class */jclass class_Employee = env->GetObjectClass(obj);/* get the field ID */jfieldID id_salary = env->GetFieldID(class_Employee, "salary", "D");/* get the field value */jdouble salary = env->GetDoubleField(obj, id_salary);salary *= 1 + byPercent / 100;/* set the field value */env->SetDoubleField(obj, id_salary, salary);
}


运行:




######################################################################################


输入double数组,输出double数组


删除Employee.java,新建MyNDK.java:

package com.zj.ndktest;/*** Created by root on 15-11-25.*/
public class MyNDK {static {System.loadLibrary("hello-jni");}public static native String Hello();public native double[] HelloDoubleArray(double[] arr);public String print(double[] arr) {StringBuffer sb = new StringBuffer();for(double dou : arr) {sb.append(dou);sb.append(" ");}return sb.toString();}
}

修改activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:id="@+id/text_view"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_array_view1"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/text_array_view2"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>

修改MainActivity.java:

package com.zj.ndktest;import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;public class MainActivity extends Activity {private TextView mTextView;private TextView mTextArray1;private TextView mTextArray2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);mTextView = (TextView)findViewById(R.id.text_view);mTextView.setText(MyNDK.Hello());double[] arr = new double[]{1,2,3,4};MyNDK my = new MyNDK();mTextArray1 = (TextView)findViewById(R.id.text_array_view1);mTextArray1.setText(my.print(arr));double[] arr2 = my.HelloDoubleArray(arr);mTextArray2 = (TextView)findViewById(R.id.text_array_view2);mTextArray2.setText(my.print(arr2));}
}

修改app/build.gradle:

apply plugin: 'com.android.application'android {compileSdkVersion 23buildToolsVersion "23.0.2"defaultConfig {applicationId "com.zj.ndktest"minSdkVersion 15targetSdkVersion 23versionCode 1versionName "1.0"ndk {moduleName "hello-jni"//moduleName "hello-employee"}}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}
}dependencies {compile fileTree(dir: 'libs', include: ['*.jar'])testCompile 'junit:junit:4.12'compile 'com.android.support:appcompat-v7:23.1.0'
}

修改Android.mk:

LOCAL_PATH := ${call my-dir}
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := main.cpp
include ${BUILD_SHARED_LIBRARY}

点击MyNDK,右键->External Tools->javah,生成com_zj_ndktest_MyNDk.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_zj_ndktest_MyNDK */#ifndef _Included_com_zj_ndktest_MyNDK
#define _Included_com_zj_ndktest_MyNDK
#ifdef __cplusplus
extern "C" {
#endif
/** Class:     com_zj_ndktest_MyNDK* Method:    Hello* Signature: ()Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *, jclass);/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleArray* Signature: ([D)[D*/
JNIEXPORT jdoubleArray JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleArray(JNIEnv *, jobject, jdoubleArray);#ifdef __cplusplus
}
#endif
#endif

修改main.cpp:

#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include "com_zj_ndktest_Employee.h"extern "C" {/** Class:     com_zj_ndktest_MyNDK* Method:    Hello* Signature: ()Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_com_zj_ndktest_MyNDK_Hello(JNIEnv *env, jclass cla) {return env->NewStringUTF("hello world");
}/** Class:     com_zj_ndktest_MyNDK* Method:    HelloDoubleArray* Signature: ([D)[D*/
JNIEXPORT jdoubleArray JNICALL Java_com_zj_ndktest_MyNDK_HelloDoubleArray(JNIEnv *env, jobject obj, jdoubleArray dou) {jsize leng = env->GetArrayLength(dou);jdoubleArray arr = env->NewDoubleArray(leng);double *a = env->GetDoubleArrayElements(arr, NULL);double *d = env->GetDoubleArrayElements(dou, NULL);for (int i = 0; i < leng; i++) {a[i] = d[i] * 2;}env->ReleaseDoubleArrayElements(dou, d, NULL);env->ReleaseDoubleArrayElements(arr, a, NULL);return arr;}}

运行:



这篇关于android ndk 入门2 - 基本方法实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1081651

相关文章

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

基本知识点

1、c++的输入加上ios::sync_with_stdio(false);  等价于 c的输入,读取速度会加快(但是在字符串的题里面和容易出现问题) 2、lower_bound()和upper_bound() iterator lower_bound( const key_type &key ): 返回一个迭代器,指向键值>= key的第一个元素。 iterator upper_bou

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

浅谈主机加固,六种有效的主机加固方法

在数字化时代,数据的价值不言而喻,但随之而来的安全威胁也日益严峻。从勒索病毒到内部泄露,企业的数据安全面临着前所未有的挑战。为了应对这些挑战,一种全新的主机加固解决方案应运而生。 MCK主机加固解决方案,采用先进的安全容器中间件技术,构建起一套内核级的纵深立体防护体系。这一体系突破了传统安全防护的局限,即使在管理员权限被恶意利用的情况下,也能确保服务器的安全稳定运行。 普适主机加固措施:

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影