Android ndk--uses Android studio to reference so libraries, jar packages and module and use JNI for correct posture

Source: Internet
Author: User

Introduction

Because of the need for JNI in the project, the previous use of JNI and so files on Eclipse, porting to Android Studio is a lot of effort, and has dealt with a number of common mistakes, and many articles on the Web have written only the approximate steps, ignoring a lot of details, In order to let the novice less detours, but also to strengthen their understanding, the step-by-step operation to record.

First, Android studio introduces Jar

Unlike eclipse, configuration build path,android Studio can be configured through the graphical interface project structure dependencies can also be configured with Gradle.build scripts .

1, first copy the corresponding JAR package to Libs or jnilibs under "Add as Library" (personal recommendation)
    • Copy and paste the jar file into the app's Libs or jnilibs directory
    • Right-click on the jar file and click "Add as Library" in the pop-up menu to add the jar file as a class library to the project
    • Select the specified class library. (High-Energy reminder: If you do not perform the next two steps, the jar file will not work, of course, you cannot use the Import statement reference.) )
2, first copy and then through the Gradle.build script configuration
    • Copy and paste the jar file into the app's Libs or jnilibs directory

    • Configure the Dependencies node (sibling to Android node) in the Build.gradle script under the app

dependencies {    compile fileTree(include: [‘*.jar‘‘libs‘)//**主要是这两句    ‘junit:junit:4.12‘    ‘com.android.support:appcompat-v7:24.0.0‘    files(‘libs/konke-android-lib.jar‘)//**编译konke-android-lib.jar}
3. Through the graphical interface of Android Studio

Open Module Setting--Project Structure --Check the corresponding module--Dependencies --"+"- -Select the corresponding jar package after execution is added to the Libs folder (that is, Libs in project mode)

Second, Android Studio relies on module

The module app relies on Zklibs:

1. Through the graphical interface of Android Studio

Open Module Setting--Project Structure --Check the corresponding module--Dependencies --"+" --Select the corresponding jar package

2, through the Gradle.build script configuration
//app的gradledependencies {    compile fileTree(include: [‘*.jar‘dir‘libs‘)    ‘junit:junit:4.12‘    ‘com.android.support:appcompat-v7:24.0.0‘    ‘com.google.code.gson:gson:2.7‘    ‘:zklibs‘)//主要是这一句}
Third, Android studio use so file

The previous Android ndk--configuration NDK and the use of Android studio to develop Hello JNI and simple packaging so introduced the so file, it is a UNIX dynamic connection library, is a binary file, its essence is the local language (c/s) Program files, function equivalent to a. dll file under Windows. The call to the Dynamic library file (*.so) in Android is done in JNI mode .

1. Introduction of so files into the project

We all know that the project structure of the Android studio and the difference in Eclipse is huge, switch to project mode and Android mode, the structure of the display is different, which also led to a lot of beginners are a bit fascinated, of course, including me, through a lot of detours, Google, StackOverflow walked many times, toss a few, finally succeeded finally, only two steps.

    • put the project in Android Studio as the project type structure, and under the Xxx/src/main directory, create a new folder named "Jnilibs" (note case, sibling to Java folder)

    • then copy and paste the so file into the "Jnilibs" directory. (in fact, the Jnilibs file can not only place so files, but also can be placed in the jar package type of library) No need to configure the additional Gradle

//当然还有另一种引入so,就是放到libs下,我不喜欢用这种方式。。。/**如果使用jniLibs文件夹导入so文件,不需要在gradle中配置了;如果将so文件添加在module的libs文件夹下,则需要在module的gradle配置中添加一下配置*/sourceSets {    main {        jniLibs.srcDirs = [‘libs‘]    }}
2. Define your own local JNI interface class 2.1, get the local method signature defined in so

With a command that is Linux:nm-d xxxx.so can also set parameters other than-D, but-D is sufficient

nm -D  libelia.so

It shows the method signature of the so library definition of the MediaTek SmartLink solution, and other information is not posted.

2.2. Implement your own local JNI interface class

After copying and pasting the so file to the "Jnilibs" folder, in general, other third-party open platform so files have been packaged in the corresponding local Java interface class together with so or other library files, we do not need to define their own local interface class, If the third party only provided the so file, then we need to define the Jni interface class (this class is not arbitrary, it must be the same as the method name defined in the so file corresponds to the one by one, that is, the package name and the class name must be consistent, otherwise it will occur when the compilation by loading error)

If so defines the local method, then the corresponding local interface class, we must satisfy four conditions:

    1. Package name is crazymo.train.jnitraining

    2. The class name is Mainactivity

    3. The defined method is named Hellojni

    4. The return value type is string

Then the general steps for defining this local interface method class are:

    1. create a corresponding package first in the project
    2. and create the corresponding public class in this package.
    3. Finally, the corresponding local interface method is defined in this class (general modifier native static return value type hellojni** Of course static is not required)
3. Loading so files

Loading so files is simple, and if you have to rely on this so to run the app, it is recommended to implement it in your own application.

 System.loadLibrary("helloJni");//加载so文件,不要带上前缀lib和后缀.so
package crazymo.train.jni;/** * @auther: Crazy.Mo * Date: 2016/10/13 * Time:15:22 * Des: */publicclass HelloJNI {    static {        System.loadLibrary("helloJni");//引入你的so库文件,不要把前面的lib添加进来    }    publicnativehelloJni();}
4, using local JNI interface class to invoke the corresponding interface method

This is more simple, and our ordinary Java class call syntax, if it is static to use the class to call, if non-static with the corresponding instance to invoke, as to how to call the local code, that part of the system will be based on your local interface package name, method name to find the corresponding C/s code, So the local interface class is often one of the culprits when we use so for errors

 PackageCrazymo.train.jni;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.widget.TextView; Public  class mainactivity extends Activity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); ((TextView) Findviewbyid (R.id.txt_usejni)). SetText (NewHellojni (). Hellojni ());//Using the Jni method}}
5. Simple use of So library project structure diagram

Four, NDK debugging

NDK debugging is not supported by default, but we can support it with just a few simple configurations.

1. Turn on JNI debugging openmodulesettings--> Check module-->build types-->jni debuggable for true--apply

2, configure Android Native-debugger run-->edit configurations--> Select the corresponding Module-->debugger-->debugger Type selected native- -apply

3. Download and install Lldb,done. V. Common errors when using so 1, java.lang.UnsatisfiedLinkError:Couldn ' t load library xxxx from loader Dalvik.system.PathClassLoader

The root cause of this anomaly is that the system does not correspond to our local method interface class, and the official point is that the JVM cannot find the native method native

    • The corresponding so caused by the crash!xxxcouldn ' t find "xxx.so" is not loaded, because APK package installation, the system will be in the APK libs directory Armeabi so copy to the application's private directory
Crash!java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file “/data/app/xxx],nativeLibraryDirectories=[/vendor/lib, /systemb]]] couldn’t find “xxx.so”
    • The loaded so is inconsistent with the ABI schema of the device being run, as long as the corresponding so file is added to the corresponding folder.

    • Java.lang.UnsatisfiedLinkError:No implementation found for XXX
      This kind of error generally comes to our local method interface class does not correspond to the methods in C/s

2. Java.lang.unsatisfiedlinkerror:com.android.tools.fd.runtime.incrementalclassloader$delegateclassloader

The reason is that the multi-party reference so, It is common for libaxx.so to exist in the corresponding folder of each schema, while another libcxx.so exists only in 32-bit corresponding Armaebi file, the other schema is not, then the program runs in the non-Armaebi architecture of the device will be a direct error strong fallback. The error log is as follows:

Ten- -  the: the:28.122 5307-5307/com.xiaoi.app.zksmarthome E/androidruntime:fatal Exception:mainProcess: Com.xiaoi.app.zkSmartHome, PID:5307java.lang.unsatisfiedlinkerror:com.android.tools.fd.runtime.incrementalclassloader$delegateclassloader[ Dexpathlist[[dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-zxing_ C557fb7a8d7e6e337af354ce06614692a32b946a-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-support-annotations-24.0.0_ Abdd7eb84ec5507286f957f2abccaca254128b0c-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_9-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_8-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_7-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_6-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_5-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_4-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_3-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_2-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_1-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-slice_0-classes.dex"Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-rxjava-1.1.8_ 75fd2ee9fdad54b1b788e8d01c74e78698f28eae-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-retrofit-2.0.0-beta4_ 3efd0604843b4a6440028ce43f72e5845c1c3325-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-picasso-2.5.2_ Badcc59626c8bf60fbd570ba883ac0f8d5c9be7a-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-okio-1.6.0_ C6c36c9266a53bff725e5087f6a3090b1d0ab593-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-okhttp-3.0.1_ A35a122a63f63f6d2b3ba59d028c055fab521b52-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-io.reactivex-rxandroid-1.2.1_ 6e88671f81f408ad9e58406d59bc0cda6a6af625-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-internal_impl-24.0.0_ 1ca3cb52067dc09725d551b03ece99cd965979ac-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-in.srain.cube-ultra-ptr-1.0.11_ B0a09794d2bb3bfed3ce82634bdccabed79fc5d0-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-gson-2.4_ 1cef8cfc76ca82a728656c88394ab94c85c46ee1-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-glide-3.6.1_ F81c2f329f31a6fbb9641a61098e423c033cd42e-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-converter-gson-2.0.0-beta4_ 75a1a6273cb28d11375dfff6cd0aa45f11079258-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-com.orhanobut-logger-1.3_ 89736aa22bffa06d17995d9ad26acdfaf3572df7-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/ Slice-com.android.support-support-vector-drawable-24.0.0_8d5d9e2412dc464146da0fdb00638a8cb0b0130d-classes.dex " Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-com.android.support-support-v4-24.0.0_ 225ce4463e0d8c3e77ccfd8c1e749bd698e46fcc-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/ Slice-com.android.support-recyclerview-v7-24.0.0_39a4b7cd3d134a80b92025fdd19f175953aa0dcc-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-com.android.support-cardview-v7-24.0.0_ 22b22b962be76ccc27cc64fad5c53d30515f6535-classes.dex "Dexfile "/data/data/com.xiaoi.app.zksmarthome/files/instant-run/dex/slice-com.android.support-appcompat-v7-24.0.0_ 4CE805B4F9E08926AE1

Workaround :
The best solution is definitely to add the corresponding so to the corresponding folder, but for some reason, can not find the corresponding so library, but also to use opportunistic way, the Armaebi under the copy to other files or delete other folders, in short, to ensure that you have I also have, can not you have I have no.

3, not yet found ... And I found a supplement later.

Android ndk--uses Android studio to reference so libraries, jar packages and module and use JNI for correct posture

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.