javaandroidc++java-native-interfacenative-methods

How to use android native code inside application project


I have a requirement where I need to access native code(inside android os) and use it in my application through jni interface.

For eg: Accessing void NuPlayer::HTTPLiveSource::start() {..} method inside HttpLiveSource.cpp.

I have found out from the from Android - Include native StageFright features in my own project that this is possible using two options:

  1. build your project using android full source tree.
  2. you can just copy include file to your project

I can't use option 1 and so am trying to use option 2... I am new to jni and so want to know:

Any pointers or detailed explanation will be very helpful.


Solution

  • What files to include inside my project?

    This depends on your project. Usually, you can use incremental approach: when your compiler complains about missing includes, go to Google source and clone the relevant piece of their Git repository. But it's also OK to download the full AOSP tree.

    Note that you will need the non-NDK shared libs to link your .so in the final stage. The easiest way is to pull all libraries from /system/lib from your target device. But you may use the emulator if you prefer.

    How to access native methods?

    You should build your native code wrapper shared library that uses JNI to communicate with your Java app. Sometimes, this is a thin layer which essentially exposes all the underlying methods in their full beauty to Java. But it's preferable to aggregate the native access (after all, every JNI traversal has its inherent overhead), and come up with a high-level easy-to-use JNI class which will take care of the native objects, threads, you-name-it.

    Is it a future proof approach?(I have seen that source files are moved to different folders depending on the OS version)

    No, it is not 100% guaranteed to work in the future, or even on one of the devices that you didn't explicitly test. This is true not only for use of native code, but for the undocumented Java APIs as well. OTOH, changes like moving source files to different folders (like what happened around 4.2 for stagefright), does not necessarily cause incompatibility.

    I am new to jni

    I would say that working with system libraries requires more than basic understanding of JNI and Android NDK. I would strongly suggest to study http://www.apress.com/9781430248279 or similar books before you dive into it.