public class MainActivity extends AppCompatActivity { // Used to load the 'JniDemo' library on application startup. static { System.loadLibrary("JniDemo"); } private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // Example of a call to a native method TextView tv = binding.sampleText; tv.setText(stringFromJNI()); // java代码调用native函数 } /** * A native method that is implemented by the 'JniDemo' native library, * which is packaged with this application. */ public native String stringFromJNI();}
在C/C++代码内里声明JNI方法原型并实现
extern "C" JNIEXPORT jstring JNICALLJava_com_example_JniDemo_MainActivity_stringFromJNI( JNIEnv* env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str());}
Local Reference:本地引用。在JNI层函数中使用的非全局引用对象都是Local Reference。它包罗函数调用时传入的jobject、在JNI层函数中创建的jobject。LocalReference最大的特点就是,一旦JNI层函数返回,这些jobject就大概被垃圾接纳。
如果不调用DeleteLocalRef,pathStr将在函数返回后被接纳;如果调用DeleteLocalRef的话,pathStr会立刻被接纳。
Global Reference:(env->NewGlobalRef(client)) )全局引用,这种对象如不自动开释,就永世不会被垃圾接纳,调用DeleteGlobalRef开释这个全局引用。
Weak Global Reference:弱全局引用,一种特别的GlobalReference,在运行过程中大概会被垃圾接纳。以是在步调中使用它之前,须要调用JNIEnv的IsSameObject判断它是不是被接纳了。