Search code examples
javaandroid-studioandroid-ndkjava-native-interfaceshared-libraries

How to use the generated .so library in another Android Project?


I’ve followed http://kn-gloryo.github.io/Build_NDK_AndroidStudio_detail/ and it works well! However, I want to use the generated .so library in a new Android application, and I simply don’t know how to do this... I’ve been struggling for days and if any step-by-step tutorial can be shared that would be helpful!

This is the Android Project MyApp which I used to generate the .so files:

enter image description here

MainActivity :

enter image description here

Java Class : MyNDK

enter image description here

header file: com_demo_ble_myapp_MyNDK.h

enter image description here

Cpp file: MyLibrary

enter image description here

And this is the structure of my new Android project useSOLib, I simply copy all the so files from MyApp\app\src\main\libs to useSoLib\app\src\main\jniLibs

enter image description here

And this is MainActivity in useSoLib:

enter image description here

I can Build-> Make Project successfully, but when I run it on the device, the app shows "Unfortunately, useSoLib has stopped." and crushed. I know I miss some steps here, but I'm new to Android Studio so I have no clue where I should start with... thank you in advance for any suggestions! :)


Solution

  • You should import MyNDK and use its instance. JNI library is related to Java class. Change the code:

    public class MainActivity extends AppCompatActivity{
       @Override
       protected void onCreate(Bundle savedInstanceState){
    
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           Log.i("MyTag", new MyNDK().getMyString());
       }
    }
    

    You can either export the MyNDK class as a jar package or create an aar bundle. Then import the Java class into your new project with JNI library.

    The post How to Build *.so Library Files into AAR Bundle in Android Studio may help you.