MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
//Load Jni library
static {
System.loadLibrary("JniLibrary");
}
//Declare Jni method
public native int callPknName(Context context);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("Tag", "length of package name: " + callPknName(this));
}
}
---------------------------------------------------------------------------------------------------------------
JniLibrary.c
#include <jni.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
JNIEXPORT jint JNICALL Java_com_example_test_pkg_callPknName (JNIEnv *env, jobject obj, jobject activity) {
//Get java context class
jclass java_class = (*env)->GetObjectClass(env, activity);
//Check if get class
if (java_class == 0) {
return 0; // did not get class
}
//Get method "java Context.getPackageName()"
//"()Ljava/lang/String;" means this method has no input argument, and returns "String" type
jmethodID java_method = (*env)->GetMethodID(env, java_class, "getPackageName", "()Ljava/lang/String;");
//Check if get method
if (java_method == 0) {
return 0; //did not get method
}
//Convert java string object to jstring
jstring java_string = (*env)->CallObjectMethod(env, activity, java_method);
//Check if get java string value
if (java_string == 0) {
return 0; //did not get method
}
//Conver jstring to char*
const char *inputLic = (*env)->GetStringUTFChars(env, java_string, NULL);
return strlen(inputLic);
}
---------------------------------------------------------------------------------------------------------------
Reference:
6.1 Callback the Constructor to Create a New Java Object in the Native Code:
Stack Overflow: