Basic Programming for Android NDK

Source: Internet
Author: User

If you do not know the role and Setup of Android NDK, you can refer to the role and Setup of Android NDK. Today, this article is based on the Android NDK development environment that has been set up, let's take a look at the implementation of NDK programming "Hello Jni.

What are the basic knowledge required for Android NDK development?

1. Familiar with Android Application Development

2. Familiar with C language (required for compiling the underlying. so Library)

3. Understand Linux (You Need To Know Some Common commands)

Next, open the "hello-jni" example project under the Sample directory under the NDK package.

As you can see, it is a common Android application with a HelloJni In the Src directory. java program, the difference is that there is an additional "jni" directory, JNI (Java Native Interface, called locally in Chinese JAVA), the role of JNI: you can use Java programs to access the libraries written in other languages (mainly C/C ++) (linux platform. so library, Windows platform. dll library), where the NDK will pass the ". mk "file" hello-jni.c "C language file compiled as needed. so library, ". mk "files do not need to be modified. If you are interested, you can use Baidu JNI for more information.

Next, we will import the sample code to eclipse. At the beginning of the study, we will only import the first HelloJni project.

Let's take a look at HelloJni. Java.

/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.example.hellojni;import android.app.Activity;import android.widget.TextView;import android.os.Bundle;public class HelloJni extends Activity{    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        /* Create a TextView and set its content.         * the text is retrieved by calling a native         * function.         */        TextView  tv = new TextView(this);        tv.setText( stringFromJNI() );        setContentView(tv);    }    /* A native method that is implemented by the     * 'hello-jni' native library, which is packaged     * with this application.     */    public native String  stringFromJNI();    /* This is another native method declaration that is *not*     * implemented by 'hello-jni'. This is simply to show that     * you can declare as many native methods in your Java code     * as you want, their implementation is searched in the     * currently loaded native libraries only the first time     * you call them.     *     * Trying to call this function will result in a     * java.lang.UnsatisfiedLinkError exception !     */    public native String  unimplementedStringFromJNI();    /* this is used to load the 'hello-jni' library on application     * startup. The library has already been unpacked into     * /data/data/com.example.hellojni/lib/libhello-jni.so at     * installation time by the package manager.     */    static {        System.loadLibrary("hello-jni");    }}

We first know this line of code: System. loadLibrary ("hello-jni"); you can access the hello-jni.c file after compilation. so library, and then TV. setText (stringFromJNI (); you can call a function in the hello-jni.c C file.

This line of code public native String stringFromJNI (); indicates the declaration of the interface and returns a String. Directly maps to the call function in the C file.

Next Look At The hello-jni.c

/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */#include 
 
  #include 
  
   /* This is a trivial JNI example where we use a native method * to return a new VM String. See the corresponding Java source * file located at: * *   apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java */jstringJava_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,                                                  jobject thiz ){#if defined(__arm__)  #if defined(__ARM_ARCH_7A__)    #if defined(__ARM_NEON__)      #define ABI "armeabi-v7a/NEON"    #else      #define ABI "armeabi-v7a"    #endif  #else   #define ABI "armeabi"  #endif#elif defined(__i386__)   #define ABI "x86"#elif defined(__mips__)   #define ABI "mips"#else   #define ABI "unknown"#endif    return (*env)->NewStringUTF(env, "huahua Hello from JNI !  Compiled with ABI " ABI ".");}
  
 

Make a slight modification to the string returned by the Java_com_example_hellojni_HelloJni_stringFromJNI function. The first parameter of the function, JNIEnv, is a structure provided by Google for Java and C interaction. The details of the structure are not further explored, the crowdsourced Security Testing Platform returns the syntax of this line of code through return to the caller stringFromJNI () of the Java file ().

The stringFromJNI () and Java_com_example_hellojni_HelloJni_stringFromJNI () methods have different names. In fact, the name after the last "_" in the C file is the name of the interface called in Java, the above is the structure of the package name. The reason for this writing is from the gcc compiler and there are fixed rules.

The following code runs the project directly on the mobile phone. An error occurs !, The logcat information is as follows:

Because the. so library does not exist yet, we need to compile it through the mk file and the C file. Open the console, go to the E: \ android-ndk-r9d \ samples \ hello-jni \ jni directory, enter ndk-build

The ndk-build script program will complete compilation, generate the. so library, and other related work. After execution, there will be two subdirectories "libs" and "obj" added in the project,

In libs, their respective. so libraries are generated based on different CPU hardware. This is not necessary for further research.

Refresh the eclipse project and add the. so library in libs. The running effect of the program is as follows:

It indicates that the upper-layer Java program calls the function OK in the bottom-layer. so library, so a simple JNI call is completed.

Let's take a look at HelloJni. Java.

Static {
System. loadLibrary ("hello-jni ");
}

This syntax indicates that when the class is loaded, System. loadLibrary ("hello-jni"); is called to load the hello-jni library. This name is written in the code in this way. In actual linux, lib3 letters are added to the left and. so letters are added to the right. It is actually the libhello-jni.so library in the libs directory we compiled. If it is in Windows, the right side will be. dll. The library names correspond to those written in the program, which is required by the operating system.

Now, let's get started with basic programming for Android NDK.

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.