Learning Android Chapter 2 NDK Translation 2

Source: Internet
Author: User
Tags time in milliseconds
JNI header file
The next step is to create the C header file based on the Fiblib Java file. How can we do this? We use Java's standard javah tool. If you want to install the Java Development Toolkit (JDK), you will find this tool in the JDK/bin directory. Now let's create the header file of C and run it in the bin directory of your project:
[Maid/bin]> javah-jni com. marakana. Fig
Javah-jni uses a Java class as a parameter. Not all classes are in the class path by default, so it is easy to change the directory to your project's bin directory. Here we assume that the current working directory is a Java class path and javah-jni com. marakana. FibLib can work.
The result is a new file named com_marakana_FibLib.h. This is the C header file that needs to be implemented next. Before implementing our local files, let's manage our projects in a short time. Although Eclipse has done a lot for us, such as installing the Android Application directory, it does not provide high-level and automated support to NDK developers. We will perform two steps manually.
Step 1: create a directory named jni in your Eclipse Fibonacci Project. Here, it is used to store all your local code and related files. In Eclipse's Package Explorer, select the Fibonacci Project, right-click New-> Folder, and create a directory.
Step 2: Put the new header file into this folder. Command:
[Maid/bin]> mv com_marakana_maid/jni/

Let's take a look at this file:

/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class com_marakana_FibLib */#ifndef _Included_com_marakana_FibLib#define _Included_com_marakana_FibLib#ifdef __cplusplusextern "C" {#endif/** Class: com_marakana_FibLib* Method: fibN* Signature: (I)J*/JNIEXPORT jlong JNICALL Java_com_marakana_FibLib_fibN(JNIEnv *, jclass, jint);/** Class: com_marakana_FibLib* Method: fibNI* Signature: (I)J*/JNIEXPORT jlong JNICALL Java_com_marakana_FibLib_fibNI(JNIEnv *, jclass, jint);#ifdef __cplusplus}#endif#endif

As you can see, this file is automatically generated and does not need to be directly modified by programmers. Here you will also observe the signatures of the two local functions we have implemented.
...
JNIEXPORT jlong JNICALL java_com_marakana_maid
(JNIEnv *, jclass, jlong );
...
JNIEXPORT jlong JNICALL java_com_marakana_maid
(JNIEnv *, jclass, jlong );
...

These are standard JNI signatures. The above two local functions, fibN and fibNI, are automatically generated according to the naming conventions (naming convention) and through the functions included in Java class com. marakana. FibLib. We can also see that both functions return jlong, a jni standard integer.
Their input parameters are also interesting: JNIEnv, jclass, and jlong. The first two parameters are usually part of the Java class and create interfaces for local code. JNIEnv is a pointer to the virtual machine environment. The second parameter points to the class or object where the function is located. jclass is a class method, and jobject is an instance method. The third parameter, jlong, is the number of the input Fibonacci algorithm, that is, our n.
We already have this header file, and it is time to provide its C language implementation.

C language implementation
We will create a C file to implement our local algorithm. For simplicity, we name it fib. c. Like the header file, it is also placed in the jni folder. Right-click the jni folder and choose New> File to create it and save it as fib. c.
Note:
When you open a C language file, you may open the file in another editor outside Eclipse. This is because Eclipse of Java does not support C language development by default. You can use C language development tools to expand your Eclipse, open Eclipse, Help-> Install New Software. Alternatively, right-click the file and select the standard Eclipse text editor from the text editor.

Next, we provide C language Fibonacci Algorithm Implementation, please see Example15-2. This C language version is almost the same as the Java version (identical ).
Example 15-2. jni/fib. c

# Include "com_marakana_fiber lib.h"/* (Note 1) * // * recursive Fibonacci algorithm (note 2) */long fiber n (long n) {if (n <= 0) return 0; if (n = 1) return 1; return fiber n (n-1) + fiber n (n-2);}/* iterative Fibonacci algorithm (Comment 3) */long fibNI (long n) {long previous =-1; long result = 1; long I = 0; int sum = 0; for (I = 0; I <= n; I ++) {sum = result + previous; previous = result; result = sum;} return result ;} /* signature of the JNI method produced in the header file (note 4) */JNIEXPORT jlong JNICALL java_com_marakana_fiber lib_fiber n (JNIEnv * env, jclass obj, jlong n) {return fiber n (n );} /* signature of the JNI method produced in the header file (note 5) */JNIEXPORT jlong JNICALL java_com_marakana_fiber lib_fiber Ni (JNIEnv * env, jclass obj, jlong n) {return fiber Ni (n );}

Note 1: We introduce com_marakana_fiber lib.h. This header file is generated by calling javah-jni com. marakana. Fiber Lib.
Note 2: The actual recursive Fibonacci algorithm. This is very similar to the Java version.
NOTE 3: How about the iterative version of Fibonacci? It is very similar to the Java version.
Note 4: This is a function provided by JNI. Copy and paste the prototype from com_marakana_FibLib.h, add the variable name, and call the corresponding C language function for this.
Note 5: Likewise, this is the signature of the iteration method.
Now we have implemented the C-language version of Fibonacci, and we will build a shared library. Then, we need a suitable makefile.

Makefile
To build a local library, Android. mk makefile must describe our files. See Example 15-3.
Example 15-3. jni/Android. mk
LOCAL_PATH: = $ (call my-dir)
Include $ (CLEAR_VARS)
LOCAL_MODULE: = fib
LOCAL_SRC_FILES: = fib. c
Include $ (BUILD_SHARED_LIBRARY)

Makefile is part of the standard Android make system. All the files we added are the specified input file (fib. c) and the specified output file (fib module ). The name of the specified module is very important. It will determine the name of the Library Based on the operating system conventions. For example, in an ARM-based system, the output is the libfib. so file.
Once we have this makefile, we are ready to initialize the build.

Build a shared library
Assuming that you have installed NDK, you can run ndk-build to build a local shared library in your project path. Ndk-build is a tool. You can find it in your NDK installation directory. We assume that you have written this Directory into the environment variable path.
At this point, you may already have a subdirectory named lib that contains your shared library. When you configure the Fibonacci application in the next section, the library will be packaged as part of the APK.

Note:
This shared library runs on the simulator by default after compilation, so it is based on the ARM architecture.

Finally, we need an application to use this library.

Fibonacci Activity
This activity is used to ask the user to enter a number and then calculate the four Fibonacci values of this number. In addition, the calculation time and result are printed on the screen. This activity basically uses the fiber lib class and the local part is switched to libfib. so. Check the code of Example 15-4.

Example 15-4. Fig. java

Package com. marakana; import android. app. activity; 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; public class Fibonacci extends Activity implements OnClickListener {TextView textResult; Button buttonGo; EditText editInput; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // Find UI viewseditInput = (EditText) findViewById (R. id. editInput); textResult = (TextView) findViewById (R. id. textResult); buttonGo = (Button) findViewById (R. id. buttonGo); buttonGo. setOnClickListener (this);} public void onClick (View view) {int input = Integer. parseInt (editInput. getText (). toString (); // comment a long start, stop; long result; String out = ""; // Dalvik-Recursivestart = System. currentTimeMillis (); // annotation 2 result = fiber Lib. fibJ (input); // comment three stop = System. currentTimeMillis (); // comment four out + = String. format ("Dalvik recur sive: % d (% d msec)", result, stop-start); // Dalvik-Iterativestart = System. currentTimeMillis (); result = fiber Lib. fibJI (input); // comment 5 stop = System. currentTimeMillis (); out + = String. format ("\ nDalvik iterative: % d (% d msec)", result, stop-start); // Native-Recursivestart = System. currentTimeMillis (); result = fiber Lib. fibN (input); // comment six stop = System. currentTimeMillis (); out + = String. format ("\ nNative recursive: % d (% d msec)", result, stop-start); // Native-Iterativestart = System. currentTimeMillis (); result = fiber Lib. fibNI (input); // comment seven stop = System. currentTimeMillis (); out + = String. format ("\ nNative iterative: % d (% d msec)", result, stop-start); textResult. setText (out); // comment 8 }}

Note 1: Convert the string you entered into an integer.
NOTE 2: Obtain the current timestamp before calculation ).
NOTE 3: We call related static functions in FibLib to display the actual Fibonacci computation. Here is the Java Recursive Implementation.
Note 4: Get Another Timestamp and subtract the previous one. The result is the calculated time in milliseconds (milliseconds ).
Note 5: iterative Implementation of Java.
Note 6: Local recursive algorithms.
Note 7: Finally, call the local iteration algorithm.

Comment 8: format the output and print it on the screen.

Linc note:

Write ndk-build to environment variables:

Open/etc/profile in a text editor
Add the following content to the end of the profile file:

NDK=/home/linc/android/android-ndk-r5bexport NDKPATH=$NDK:$PATHexport PATH

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.