JNI is basically configured and used in Android Studio 2.2

Source: Internet
Author: User
Tags java reference
JNI is basically configured and used in Android studio

JNI basic configuration and use of what in Android Studio to build projects using Ndkbuilder

what? Jni
Java Native Interface It allows Java code to interact with code written in other languages. JNI is a local programming interface that enables Java code that runs inside a Java Virtual machine (VM) to interoperate with applications and libraries written in other programming languages, such as C, C + +, and assembly language.
Since the classes in the Android application layer are written in Java, these Java classes are compiled into a DEX-style bytecode and must be performed by Dalvik virtual machines (vm:virtual Machine). Ndk
Native Develop kit (Local development Kit), similar to JDK, is just a set of tools that can help developers in Android development, it uses the JNI mechanism. The difference between the two
JNI java Native Interface Java invoke the technical term of the local interface
NDK Native Developer Kit Google gives developers the toolkit to use Ndkbuilder for project build downloads NDK (installed, skipped)

Enter Project Setup interface


without installation, direct download can be, PS. will be stuck for a long time when the final installation, patiently waiting for the installation to complete

The configuration App,build.gradle file is added to the Defaultconfig node in the app's Build.gradle, the Build.gradle file in the project to run.

    NDK {
            modulename "Ndkjnidemo"   //generated
            so name ldlibs "log", "Z", "M"    ///Add dependent library file, because there is log print etc//non required
            Abifilters "Armeabi", "armeabi-v7a", "x86"/output specifies the so library under three ABI architectures and is currently optional. Generate all} if not filled out
        
Create a local need to create code that calls C, for example, use a method to get a string
Create a new tool class jniutils, use C to get a string, and then show it to a
public class Jniutils {public
    static native String getstringformc ();
    ... Can have a lot of native code
}

* Use the Native keyword to invoke a local method, which can be used to implement * generation using the C + + language. h,c/c++ header file (familiar with C's know, can have no header file, header file just defines all the methods in the class (no concept of class in C))
When you build or rebuild or clear a program, all of the class files in the project are generated in the Build/intermediates/classes/debug directory.
command line access to the Debug directory CD < path > compilation directives

    Javah-jni com.wobiancao.ndkjnidemo.ndk.JniUtils

note Here Javah-jni is followed by the full path of the Jniutils class, if the Javah newspaper does not exist or not, your Java environment is not configured well.
4. After compiling, a. h file will be generated in the debug directory, and it will be named in a very long way, basically a full path naming method.
Jonathanhsia_com_ndktest_utils_jniutils.h

5. Copy files to the Main/jni directory in the project, if not directly created to write C method implementation
In the JNI directory, create a new C + + file, refer to the header file, make a copy of the Java + + method to invoke it, return a string, and statically import the so-C + + generated so package in Jniutils

    static {
        system.loadlibrary ("Ndkjnidemo");//before the so name set in Build.gradle must be consistent
    }

at this point, the Java code can be invoked to the code implemented with C/E + +.

"PS. After run, in the Build/intermediates/ndk/debug/lib directory will appear in the Build.gradle configured in the three CPU architecture so packet, this time delete the JNI directory of the source code, The direct copy of these so packages into the project can be directly used.

met the pit
1. C + + can not format the code, or it will appear, the compilation passed (May compile errors, but did not prevent the operation), can not run, the report can not find the exception of so packet
2. The first run may be reported

ERROR:NDK integration is deprecated at the current plugin. Consider trying the new experimental plugin. For details, Http://tools.android.com/tech-docs/new-build-system/gradle-experimental. The Set "Android.usedeprecatedndk=true" in gradle.properties to continue using the current NDK integration.

Such a mistake, follow the prompts in the Gradle.properties file to add Android.usedeprecatedndk=true field can
3. do not support Intant run
4. Two C at the same time to achieve H method, will be an error, not allowed, logically is not allowed;
5. The position of the jniutils can not be arbitrarily already, because and the C + + file is one by one corresponding reference relationship

### #使用cmake进行项目的构建
* 1.cmake Editing is a new feature that is supported by Android Studio 2.2 to simplify the JNI development process and use studio2.2 to create a new project that will allow you to check in CMake

2. When the include C + + support is checked, when the project is created, there will be more than the interface, select the C + + standard, where the settings in the app Build.gradle Defaultconfig will increase the setting

       Externalnativebuild {
            CMake {
                cppflags "-frtti-fexceptions"//This tag is the first option, and if you use the C++11 standard, use
                //cppflags "- Std=c++11 "
            }
        }
3. Under the Android node in Build.gradle, the configuration is increased to specify the path to generate the so file configuration file
  Externalnativebuild {
        cmake {
            path ' CMakeLists.txt
        }
    }}
4. Create Java code that needs to call C + + code, same as Ndkbuilder
public class Jniutils {public
    static native String getStrFromC2 ();
}
5. In the project src/main/create a CPP directory, which can directly create the CPP source code, and Ndkbuild, the same method in the source codes written by C/s + + must be the full path of the method name, and then start with Java, split using underline.
#include <jni.h>
#include <string>

extern "C"
jstring
Java_com_ndkcmaketestapp_utils_ JNIUTILS_GETSTRFROMC2 (jnienv *env, Jobject thiz) {
    std::string hello = "Hello from c + + two!";
    Return Env->newstringutf (Hello.c_str ());
}
specific configuration in the 6.cmakelists.txt file
Cmake_minimum_required (VERSION 3.4.1) #指定cmake版本
add_library (Form SHARED src/main/cpp/form.cpp) # Hello is the name of the generated so file, and the name of the CPP file is the same
target_link_libraries (Hello log android) # added here, log link library
7. Add code to the so library in Java code to make the code effective
public class Jniutils {

    //Used to load the ' Native-lib ' Library on application startup.
    static {
        system.loadlibrary ("form")//The name of the form library here needs to be the same as the same} public static as configured in CMakeLists.txt
    native String getStrFromC2 ();
}


8. After run succeeds, the. Externalnativebuild directory is added above the build directory, where. Externalnativebuild/cmake/debug/obj contains all the generated so packages, The same copy to the Jnilibs in the project can be used directly

CMake Advantage 1. You can add a breakpoint to the C + + code directly, debug the method of 2.java reference C + +, you can directly CTRL + + left into 3. For include header files, or libraries, you can enter 4 directly. You do not need to configure command line operations. Manual build header file, no need to configure Android.usedeprecatedndk=true property

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.