Janaki
Janaki

Reputation: 145

How to link and call function of prebuild static native library from android studio

I need to change pitch and time stretching of an audio. For this I am using prebuild static library. Currently I am having libZtxAndroid.a static library and corresponding header file which contains function declaration. But I don't know how to load this library in my android studio app and call native function from java code. I explored many links and tried to load this library. But all attempts are failed. This is the one link which I have tried last time https://tariqzubairy.wordpress.com/2012/03/12/use-of-prebuild-static-library-compiled-with-android-toolchain/

Also I am using FFMPEG shared library and MP4Parser (https://github.com/sannies/mp4parser) library in this app for adding water mark to video and merging audio respectively. Can any one help from basics.

  1. How to load static library?
  2. Where I need to place that static library?
  3. Where I need to create jni folder (folder structure)?
  4. How to call function available in that static library with the help of header file from java code?

Upvotes: 3

Views: 2914

Answers (1)

Germán Diago
Germán Diago

Reputation: 7663

You need to do several things:

  1. Compile a dynamic library. This is a .so file in Android. You can do this with the android ndk.
  2. There is a directory in every android project, I am saying from the top of my head, but I think it is in a jni subdirectory where you must put your library.
  3. You should wrap your library in JNI. Place them as the advice in this other question: JNI folder in Android Studio
  4. If you have something like this in android:

    Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz )

where Java_comp_example_hellojni_HelloJni is your project name, you have to do from Java, assuming the name of your lib is libmylib.so:

public class HelloJni {
  static {
    System.LoadLibrary('mylib');
  }

  public native stringFromJni();
}

Note that the native library name does not need the lib prefix and the .so suffix. Note also that you do not need any header file from C++, you just load the library from Java and declare a native function. The library should be already compiled and in the right directory before the Java project uses it.

Be careful at loading: if you use the shared version of the standard library, you will also need to add it to your static { section in Java for loading it, before your library.

Upvotes: 2

Related Questions