Search code examples
android-ndkjava-native-interfaceandroid-gradle-pluginandroid-studio-2.2tess-two

Building tess-two into a project using Android Studio's gradle build


There are answers about getting the tess-two project integrated into an Android project within Android Studio, but many are out-dated and none used the current capabilities defined here:

Using Android Studio 2.2 and higher, you can use the NDK to compile C and C++ code into a native library and package it into your APK using Gradle, the IDE's integrated build system. Your Java code can then call functions in your native library through the Java Native Interface (JNI)

What specific steps would be required to make tess-two functionality a part of the resulting APK, using functionality within Android Studio, rather than external file placement, manipulation and command line tools? So taking the building, creation of *.so files into the IDE. Specifically using just Android Studio's integrated build system (Gradle) as described here.

1. Start a new project

starting a new Android Studio project with C++ support

2. Import Tess-Two into the project

import tess-two as a module in the new project

2b. Add any needed plug-ins

add to tess-two build.gradle to pull required plug-ins

3. Add code in the main activity to get native functionality

static import of tess-two native files

4. Configure Android Studio build so that native functionality is available

This is where the specifics are required


Solution

  • 4. Configure Android Studio build for native functionality

    4a. Link C++ Project with Gradle

    First, check the tess-two project for build files. You may select CMakeLists.txt or Android.mk files. Both are currently supported.

    checking project build config files

    In this case, I used ndk-build, which seemed like a good bet for integrating the native code.

    Linking C++ project

    For more information, see Android Studio documentation

    4b. Manage Long Commands

    In Windows, errors may be encountered if the command length grows too large. To prevent problems, use LOCAL_SHORT_COMMANDS AND APP_SHORT_COMMANDS in the Android.mk file.

    Adding attributes that reduce command length

    The "e=87" error is what you are avoiding by doing this:

    The parameter is incorrect error 87 message

    For more on that topic, see stackoverflow question about error 87.

    4c. Add Module Dependency for tess-two

    In File > Project Structure > Dependencies use the + to add the tess-two dependency:

    add tess-two as a dependency

    4d. Build the Project and check .apk file for .so files

    The build, which takes a long time, should complete now. Validate that the .apk file contains the .so files, created during the build. With the tess-two libraries in an static initializer, run the project on your Android device:

    apk file with tess-two .so files and running test app