packagecom.example.luonative;importandroidx.appcompat.app.AppCompatActivity;importandroid.os.Bundle;importandroid.util.Log;importandroid.widget.TextView;importcom.example.luonative.databinding.ActivityMainBinding;publicclassMainActivityextendsAppCompatActivity{// Used to load the 'luonative' library on application startup.static{System.loadLibrary("luonative");}privateActivityMainBindingbinding;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);binding=ActivityMainBinding.inflate(getLayoutInflater());setContentView(binding.getRoot());// Example of a call to a native methodTextViewtv=binding.sampleText;tv.setText(stringFromJNI());while(true){try{Thread.sleep(1000);}catch(InterruptedExceptione){e.printStackTrace();}Log.d("LuoHun",stringFromJNI());}}publicnativeStringstringFromJNI();}
native代码:
1
2
3
4
5
6
7
8
9
10
11
12
//libluonative.so
#include<jni.h>#include<string>//JNI函数的命名规则:Java_PackageName_ClassName_MethodName
extern"C"JNIEXPORTjstringJNICALLJava_com_example_luonative_MainActivity_stringFromJNI(JNIEnv*env,jobject/* this */){std::stringhello="Hello from C++";returnenv->NewStringUTF(hello.c_str());}
packagecom.example.luonative;importandroidx.appcompat.app.AppCompatActivity;importandroid.os.Bundle;importandroid.util.Log;importandroid.widget.TextView;importcom.example.luonative.databinding.ActivityMainBinding;publicclassMainActivityextendsAppCompatActivity{// Used to load the 'luonative' library on application startup.static{System.loadLibrary("luonative");}privateActivityMainBindingbinding;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);binding=ActivityMainBinding.inflate(getLayoutInflater());setContentView(binding.getRoot());// Example of a call to a native methodTextViewtv=binding.sampleText;tv.setText(stringFromJNI());while(true){try{Thread.sleep(1000);}catch(InterruptedExceptione){e.printStackTrace();}Log.d("LuoHun",stringFromJNI());}}publicnativeStringstringFromJNI();}
//libluonative.so
#include<jni.h>#include<string>jstringJNICALLLuoDynamicNative(JNIEnv*env,jobject/* this */){std::stringhello="Hello from C++ LuoHun";returnenv->NewStringUTF(hello.c_str());}JNIEXPORTjintJNI_OnLoad(JavaVM*vm,void*reserved){JNIEnv*env;vm->GetEnv((void**)&env,JNI_VERSION_1_6);JNINativeMethodmethods[]={"stringFromJNI","()Ljava/lang/String;",(void*)LuoDynamicNative};env->RegisterNatives(env->FindClass("com/example/luonative/MainActivity"),methods,1);returnJNI_VERSION_1_6;}