Search code examples
androidandroid-fragmentsjava-native-interface

What is the best practice for using Android JNI and fragments?


What is the best practice for using JNI to call into an application which uses fragments?

For instance, I would like to use the master detail flow template (scroll down on this page https://developer.android.com/tools/projects/templates.html) to create a nice list of items which get populated by calls from the C (JNI) side. However, this template makes use of fragments, which has left me a little confused as I am relatively new to Android development.

Should I create a public native function in one of the activities, or should it be in the fragment? If it's the activity, how do I then make the fragment update whenever a new item gets added?

Thanks!

Edit: question title changed for clarity.


Solution

  • Should I create a public native function in one of the activities, or should it be in the fragment?

    Place your native functions in your activity. Fragments, generally speaking, have a much shorter life span than activities do. Additionally, several instances of the same Fragment subclass can be displayed at once. So by loading your library in the activity instead of the fragment, you're reducing the load on the system in general.

    If it's the activity, how do I then make the fragment update whenever a new item gets added?

    You can use getSupportFragmentManager().getFragments(); to get a List<Fragment>. From there, there are several ways in which you can select a fragment and call a function on it.