Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to get started with NDK in Android

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, the editor will take you to understand how to introduce Android to NDK. The knowledge points in the article are introduced in great detail. Friends who think it is helpful can browse the content of the article with the editor, hoping to help more friends who want to solve this problem to find the answer to the problem. Let's follow the editor to learn more about "how to get started with NDK in Android".

We'll show you how to install Android NDK and start using it. At the end of this tutorial, you will create your own project to simply call native C code from Java code.

Prior experience

Before we begin, we need to take some time to understand the difficulty of this tutorial. Its mark is "advanced". It is marked "advanced" because we authors want to make sure that you meet the following requirements:

You have experience in Java and C languages.

You can adapt to command line operation.

You know how to learn about the versions of your Cygwin, awk, and other tools.

You can adapt to Android Development.

You have an effective Android development environment (at the time of writing, the author uses Android 2.2)

You can use Eclipse or you can easily apply the Eclipse instructions to your own IDE.

Even if you do not meet these conditions, you are certainly welcome to read this tutorial, but you may encounter difficulties in some steps, which will be easily solved if you meet the above conditions. In other words, even if you think you are a mobile developer veteran, using NDK is still easy to encounter difficulties and troubles. Please note that you may have to troubleshoot yourself to make everything work properly in your development system.

The complete open source code download for the sample project is provided below.

Instructions for when to use NDK

Well, if you are reading this tutorial, you may already be considering using NDK in your Android project. However, we want to take a moment to discuss why NDK is so important, when to use it, and-- equally important, when not to use it.

In general, you only need to use NDK if your application is really a processor killer. In other words, the algorithm you design uses all the processor resources in DalvikVM and is more advantageous to run natively. Also, don't forget that in Android 2.2, the JIT compiler improves the efficiency of similar code.

Another reason for using NDK is that it is easy to migrate. If you have a lot of C code in your existing application, using NDK can not only speed up the development process of your project, but also keep changes synchronized between your Android and non-Android projects. This is especially true for OpenGL ES applications written for other platforms.

Don't think that using native code can improve the efficiency of your application. The conversion between Java and native C adds some resource overhead, so this is really necessary only if you have some tasks that consume processor resources.

Step 0: download the tool

All right, let's get started. You need to download NDK. Let's start the download first, because you can check to make sure that the rest of the tools you need are in the correct version during the download process.

Download the NDK for your operating system from the Android website.

Now, check your tool version against the following:

If under Windows, Cygwin 1.7 or later

Upgrade awk to * * version (we are using 20070501)

GNU Make 3.81 or later (we use 3.81)

If any of these versions are too old, please upgrade before continuing.

Step 1: install NDK

Now that NDK has been downloaded (right? You need to unzip it Unzip it and put it in the appropriate directory. We put it in the same directory as Android SDK. Remember where you put it.

Now, you may want to add the NDK tool to the path settings. If you are in Mac or Linux, you can use your native path settings to do this. If you are in the Cygwin under Windows, you need to set the path settings for Cygwin.

Step 2: create a project

Create a regular Android project. To avoid future problems, the path of your project must not contain spaces. Our project has a package called "com.mamlambo.sample.ndk1" with a default Activity-- called "AndroidNDK1SampleActivity" that you will see later.

Create a directory called "jni" at the top of the project-this is where you put the native code. If you are familiar with JNI, you will know that Android NDK is largely based on the concept of JNI-it is essentially a JNI with limited header files compiled in C.

Step 3: add some C code

Now, in the jni folder, create a file called native.c. Write the following C code to the file at first, and we'll add another function later:

# include # define DEBUG_TAG "NDK_AndroidNDK1SampleActivity" void Java_com_mamlambo_sample_ndk1_AndroidNDK1SampleActivity_helloLog (JNIEnv * env, jobject this, jstring logThis) {jboolean isCopy; const char * szLogThis = (* env)-> GetStringUTFChars (env, logThis, & isCopy); _ _ android_log_print (ANDROID_LOG_DEBUG, DEBUG_TAG, "NDK:LC: [% s]", szLogThis) (* env)-> ReleaseStringUTFChars (env, logThis, szLogThis);}

This function is actually very simple. It takes a string parameter of a Java object, converts it to C-string, and then writes it to LogCat.

But the name of the function is important. It follows the specific word "Java", followed by the package name, then the class name, and then the method name, as defined in Java. Each part is separated by an underscore, not a dot.

The first two parameters of this function are also important. * the parameter is the JNI environment, which and the helper function will be called frequently. The second argument is the Java object to which the function belongs.

Step 4: call native code from Java

Now that you've written the original code, let's go back to the Java side. In the default Activity, create a button according to your preference and add a button handler. From the button processor, make a call to helloLog:

HelloLog ("This will log to LogCat via the native call.")

Then you have to add the function declaration on the Java side. Add the following declaration to your Activity class:

Private native void helloLog (String logThis)

It tells the compilation and linking system that the method will be implemented in native code.

*, you need to load the library into which the native code is eventually compiled. Add the following static initialization program to the Activity class to load the library by name (the name of the library is up to you, which will be used in the next step):

Static {System.loadLibrary ("ndk1");}

Step 5: add a Make file for native code

In the jni folder, now you need to add the makefile to be used in the compilation. The file must be named "Android.mk". If you named the file native.c and the library ndk1, then the content of Android.mk should be like this:

LOCAL_PATH: = $(call my-dir) include $(CLEAR_VARS) LOCAL_LDLIBS: =-llog LOCAL_MODULE: = ndk1 LOCAL_SRC_FILES: = native.c include $(BUILD_SHARED_LIBRARY)

Step 6: compile the native code

Now that your native code is complete and the make file is ready, it's time to compile the native code. From the command line (Windows users are under Cygwin), you need to run the ndk-build command from the root of your project. The ndk-build tool is in the NDK tool catalog. Adding it to our path is the most convenient way.

In later compilations, if you use the "ndk-build clean" command, you can make sure that everything is recompiled.

Step 7: run the code

Now you are ready to run the code. Load the project in your favorite simulator or handheld device, view LogCat, and click the button.

Two things could happen. First of all, it may be working properly. In that case, congratulations! But you may want to keep reading. You may also get errors like "Could not execute method of activity" in LogCat. This is normal. It just means you missed a step. This can easily happen with Eclipse. Typically, Eclipse is set to recompile automatically. If it doesn't know that something has been modified, it won't automatically recompile and relink. In this case, Eclipse doesn't know you compiled the native code. So, "cleaning" the project (click item (Project)-> clear (Clean) in the Eclipse toolbar) to force Eclipse to recompile.

Step 8: add another native function

The next function will demonstrate not only the ability to return values, but also the ability to return objects such as strings. Add the following functions to native.c:

Jstring Java_com_mamlambo_sample_ndk1_AndroidNDK1SampleActivity_getString (JNIEnv * env, jobject this, jint value1, jint value2) {char * szFormat = "The sum of the two numbers is:% I"; char * szResult; / / add the two values jlong sum = value1+value2; / / malloc room for the resulting string szResult = malloc (sizeof (szFormat) + 20); / / standard sprintf sprintf (szResult, szFormat, sum) / / get an object string jstring result = (* env)-> NewStringUTF (env, szResult); / / cleanup free (szResult); return result;}

In order to compile properly, you will need to add a declaration of include stdio.h. Also, in response to this new native function, add the following declaration to your Activity Java class:

Private native String getString (int value1, int value2)

You can now set its function as you like. We use the following two calls and output:

String result = getString (5 Result2 2); Log.v (DEBUG_TAG, "Result:" + result); result = getString (105,1232); Log.v (DEBUG_TAG, "Result2:" + result)

Going back to the C language functions, you will notice that we have done a lot of things. First, we need to create a buffer when we use the sprintf () call in the malloc () function. This makes sense if you don't forget to clean up the results by using the free () function. Then, to return the results, you can use a JNI helper function called NewStringUTF (). This function basically takes a C language string to create a new Java object. This new string object can then be returned as a result, and you can use it as a regular Java string object in the Java class.

Instruction set, compatibility, etc.

Android NDK requires Android SDK 1.5 or later. In the new version of NDK, there are new header files that can be used to expand access to some API-- especially the OpenGL ES library.

However, those are not the compatibility we are talking about. This is native code that is compiled by the processor architecture when in use. So, one of the questions you have to ask yourself is what processor architecture does it support? In the current NDK (as of this writing) it only supports the ARMv5TE and ARMv7-An instruction sets. By default, the target architecture is set to ARMv5TE, which can run on Android devices that use ARM chips.

It expects to support other instruction sets (which mention x86) in the future. There is an interesting potential: the NDK solution does not work for all devices. For example, there are Android tablets on the market that use Intel Atom processors with x86 instruction sets.

So what about NDK on the simulator? The simulator runs a real virtual machine, including full processor virtualization. Yes, this means that running Java in a virtual machine is equivalent to running a virtual machine in a virtual machine.

Thank you for your reading. The above is the whole content of "how to get started with NDK in Android". Friends who learn to learn to do it quickly. I believe that the editor will certainly bring you better quality articles. Thank you for your support to the website!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report