Learning Journey Based on Android NDK-Data Transmission 1 (basic data type and array transmission)

Source: Internet
Author: User

In some previous articles, data transmission between the upper layer and the middle layer is involved. In short, the use of parameters and returned values. This is because the most important thing to do in the middle layer is data transmission and conversion. Next we will introduce this knowledge.
Data transmission can be divided into transmission of the basic data type and transmission of the reference data type, because array transmission is also quite special (in fact, arrays are also the reference type), so here we also talk about it separately.
 
1. Main Process

1. Transmission of Basic Data Types
A) The upper layer defines an native method and requires an int parameter to return an int value.
B) The method corresponding to the upper layer of JNI prints the int data transmitted from the upper layer and returns the int data.
C) The upper layer receives the value returned by the native method and displays it in the UI.
 
 
2. array Transmission
A) The upper layer defines an native method and requires an int array to return an int array.
B) JNI corresponds to the upper-layer method, extracts the data processing and printing from the upper-layer passed array, stores the data in the new array, and finally returns the array to the Java layer.
C) The upper layer receives the array returned by native and processes it into a string, which is displayed in the UI.
 
 
2. Design and Implementation

1. The interface design is as follows:


Old look, very awkward, hey
The code is not posted here. If you need the code, you can download it directly at the end of the article.
2. Key Code Description
 
Java upper layer:

Public native int getDoubleNumber (int num );
 
Public native int [] getArrayDoubleNumber (int [] nums );
MainActivity. java
  
Package com. duicky;
 
Import android. app. Activity;
Import android. content. Context;
Import android. OS. Bundle;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. EditText;
Import android. widget. TextView;
/**
* Data Transmission
*
* @ Author luxiaofeng <454162034@qq.com>
*
*/
Public class MainActivity extends Activity {

// LOCAL_MODULE: = NDK_06 in your mk configuration file
Private static final String libSoName = "NDK_06 ";
Private Context mContext = null;

Private int num = 0;
Private int [] nums;

Private Button btnCalculate = null;
Private Button btnCalculateArray = null;
Private EditText etNum = null;
Private EditText etArrayNum = null;
Private TextView tvDoubleNum = null;
Private TextView tvArrayDoubleNum = null;


/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
MContext = this;
InitViews ();
}

/**
* Initialize the control.
*/
Private void initViews (){
BtnCalculate = (Button) findViewById (R. id. btn_calculate );
BtnCalculateArray = (Button) findViewById (R. id. btn_calculate_array );
EtNum = (EditText) findViewById (R. id. et_num );
EtArrayNum = (EditText) findViewById (R. id. et_array_num );
TvDoubleNum = (TextView) findViewById (R. id. TV _double_num );
TvArrayDoubleNum = (TextView) findViewById (R. id. TV _array_double_num );
BtnCalculate. setOnClickListener (new MyOnClickListener ());
BtnCalculateArray. setOnClickListener (new MyOnClickListener ());
}
 
Private void calculateArray (){
If (getArrayNums ()){
SetArrayNums ();
}
}
 
Private void calculate (){
If (getNum ()){
SetNum ();
}
}

Private boolean getNum (){
Try {
Num = Integer. valueOf (etNum. getText (). toString ());
} Catch (NumberFormatException e ){
EtNum. setText ("");
TvDoubleNum. setText ("");
LogUtils. toastMessage (mContext, "incorrect input. Please enter a number again ");
Return false;
}
Return true;
}

Private void setNum (){
Int doubleNum = getDoubleNumber (num );
LogUtils. printWithLogCat ("JNIMsg", "c jni --> Java: num =" + doubleNum );
TvDoubleNum. setText (String. valueOf (doubleNum ));
}

Private boolean getArrayNums (){
String str = etArrayNum. getText (). toString ();
If (str. length () <= 0 ){
EtArrayNum. setText ("");
TvArrayDoubleNum. setText ("");
LogUtils. toastMessage (mContext, "Please input according to the format ");
Return false;
}
System. out. println (str );
If (str. endsWith (".")){
Str = str. substring (0, str. length ()-2 );
}
System. out. println (str );
String [] strArray = str. split (",");
Int len = strArray. length;
Nums = new int [len];
For (int I = 0; I <len; I ++ ){
Try {
Nums [I] = Integer. valueOf (strArray [I]);
System. out. println (nums [I]);
} Catch (NumberFormatException e ){
EtArrayNum. setText ("");
TvArrayDoubleNum. setText ("");
LogUtils. toastMessage (mContext, "incorrect input. Please input an array again ");
Return false;
}
}
Return true;
}

Private void setArrayNums (){
Int [] doubleArrayNums = getArrayDoubleNumber (nums );

If (doubleArrayNums = null | doubleArrayNums. length <= 0 ){
LogUtils. toastMessage (mContext, "not converted successfully ");
Return;
}

String str = "";
For (int I = 0; I <doubleArrayNums. length; I ++ ){
Str + = doubleArrayNums [I] + ".";
}
Str = str. substring (0, str. length ()-1 );
TvArrayDoubleNum. setText (str );
}

Class MyOnClickListener implements OnClickListener {
 
@ Override
Public void onClick (View v ){
Switch (v. getId ()){
Case R. id. btn_calculate:
Calculate ();
Break;
Case R. id. btn_calculate_array:
CalculateArray ();
Break;
}
}
}
 
/**
* Calculate 2 times the number
*
* @ Param num
*
* @ Return
*/
Public native int getDoubleNumber (int num );


/**
* Calculate twice the array value
*
* @ Param num
*
* @ Return
*/
Public native int [] getArrayDoubleNumber (int [] nums );

/**
* Load the so library file generated by JNI
*/
Static {
System. loadLibrary (libSoName );
}
}
  
Define two native methods. The first is used to test the basic data type for transmission, and the second is used to test the transmission array.

Android. mk File

LOCAL_PATH: = $ (call my-dir)
 
Include $ (CLEAR_VARS)
 
LOCAL_C_INCLUDES: = $ (LOCAL_PATH)/include
 
LOCAL_LDLIBS + =-L $ (SYSROOT)/usr/lib-llog
 
LOCAL_MODULE: = NDK_06
 
LOCAL_SRC_FILES: = \
 
Transmission. c
 
Include $ (BUILD_SHARED_LIBRARY)
  
You know it. If you don't understand it, click the introduction to the Android. mk file.
 
JNI Middle Layer

Transmission. c

# Include <string. h>
# Include <jni. h>
# Include <android/log. h>
 
JNIEnv * jniEnv;
 
 
Jint
Java_com_duicky_MainActivity_getDoubleNumber (JNIEnv * env, jobject thiz, jint num)
{
If (jniEnv = NULL ){
JniEnv = env;
}
// Obtain the numbers passed in Java
_ Android_log_print (ANDROID_LOG_INFO, "JNIMsg", "Java --> c jni: num = % d", num );
// Returns 2 times the number to Java
Return num * 2;
}
 
JintArray
Java_com_duicky_MainActivity_getArrayDoubleNumber (JNIEnv * env, jobject thiz, jintArray nums)
{
If (jniEnv = NULL ){
JniEnv = env;
}
 
If (nums = NULL ){
Return NULL;
}
 
// Obtain the length of the array passed by Java
Jsize len = (* jniEnv)-> GetArrayLength (jniEnv, nums );
 
_ Android_log_print (ANDROID_LOG_INFO, "JNIMsg", "Java --> c jni: len = % d", len );
 
If (len <= 0 ){
Return NULL;
}
 
// Create a new jintArray with len Length
JintArray array = (* jniEnv)-> NewIntArray (jniEnv, len );
 
If (array = NULL ){
Return NULL;
}
 
// Store the array passed by Java with jint *
Jint * body = (* env)-> GetIntArrayElements (env, nums, 0 );
 
Jint I = 0;
Jint num [len];
For (; I <len; I ++ ){
Num [I] = body [I] * 2;
_ Android_log_print (ANDROID_LOG_INFO, "JNIMsg", "Java --> c jni: nums [% d] = % d", I, num [I]);
}
 
If (num = NULL ){
Return NULL;
}
 
// Assign values to the array to be returned
(* JniEnv)-> SetIntArrayRegion (jniEnv, array, 0, len, num );
 
Return array;
}
  
3. Running result

Test Basic Data Type Transmission: Enter 22 and click calculation to obtain result 44.


 
View print information: view the upper-layer output result


 
Test Reference Data Type Transmission: Enter 100, 55 (the comma is the half-width input in English), click Generate, output


View print information: view the JNI layer output result


 
 
The above is a small example of the transmission of basic data types and arrays in Java --- JNI. Other basic data types and arrays can be transmitted in the same way as above.
 
 
 
4. Notes

What you must know is:
1) Add parameters after (JNIEnv * env, jobject thiz), such as: (JNIEnv * env, jobject thiz, jintArray nums)
2) Get the length of the array jsize len = (* jniEnv)-> GetArrayLength (jniEnv, nums );
3) create an array jintArray array = (* jniEnv)-> NewIntArray (jniEnv, len). If you create another array, NewIntArray must be changed accordingly.
4) obtain the elements in the array:
1. (* env)-> GetIntArrayElements (env, nums, isCopy), return all data. If isCopy is not NULL, then * isCopy is set to JNI_TRUE if a copy is made; if no copy is made, it is set to JNI_FALSE.
2. (* env)-> GetIntArrayRegion (env, array, start, len, buffer), copy data with a length of len from start to buffer
5) set the elements in the array
1. (* env)-> SetIntArrayRegion (env, array, start, len, buffer), copy the data buffer with the length of len from start to array.
 
 
If you have any questions, please leave a message. Your personal skills are limited. If you have any mistakes, please point out that you are not comprehensive enough. Thank you,
 
 
This article is from duicky's blog

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.