2

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! :)

Alison
  • 431
  • 6
  • 19
  • Probably there's something wrong with your native code. Have you tried to use log or gdb to check which line of your code caused the exception? – yushulx May 23 '16 at 06:10
  • Thanks for the reply! In the MainActivety of the project MyApp(which I used to generate .so library), I’ve newed an instance of MyNDK, called the native function getMyString, and it runs successfully on the device, I can also see the correct returned String in my logcat, so I assume the native C++ function works well. Just when I try to access the generated .so library from other Android project with a different package name, it crushed... I also add my header and cpp files above for reference. – Alison May 23 '16 at 06:41
  • Your code is wrong. See my answer. You have to export the Java Class and import it into your new project with the *.so file. – yushulx May 23 '16 at 07:15

1 Answers1

1

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.

yushulx
  • 11,695
  • 8
  • 37
  • 64
  • I’m trying to make an aar but so far got no luck... I’ll edit my question with some pics to show what I’ve done, please let me know if there's anything I missed, thanks a lot! :) – Alison May 23 '16 at 09:33