Issue
I am diving into the ndk stuff and I've managed to make a simple library and call it from my activity.
In order to test it, in my Activity
I have used:
static {
System.loadLibrary("my-lib");
}
public native static String callNativeFunction(Context context);
This means that calling MyActivity.callNativeFunction(context)
does return the String
value from my Cpp function.
I have 2 questions:
The
loadLibrary
is made in my main activity, however I want to be able for instance, to call thecallNativeFunction
function from anIntentService
when the activity may be closed or from other places of my app. How can I properly load the library and have it available from all places of the app?Since this is a simple function that I'll use in my project, is there anything else specific to do on release? From https://developer.android.com/studio/projects/add-native-code.html it seems that Gradle builds for all supported abis and adds them into the apk.
Solution
- You need to load the library once. This can also be done in your
Application
class. Once the library is loaded, you can call the defined native methods from the appropriate classes defined in yourcpp
class
Application class :
public class SRApplication extends Application {
static {
System.loadLibrary("my-lib");
}
@Override
public void onCreate() {
super.onCreate();
}
}
CPP :
extern "C"
jstring
Java_com_example_service_ExampleService_getNativeString (
JNIEnv* env,
jobject /* this */) {
return env->NewStringUTF("yo");
}
Your Service :
package com.example.service.ExampleService;
public class ExampleService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
String nativeString = getNativeString();
return null;
}
public native String getNativeString();
}
If you don't have specific code for different cpu variants, you don't need to explicitly handle anything, the default
externalNativeBuild { cmake { cppFlags "" } }
is sufficient.
Answered By - Alim Parkar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.