package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
public void showFrame(){
Log.d("chenjx","chenjx");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
#include <jni.h>
#include <string>
jclass myclass;
jmethodID methodId;
jobject g_MainActivity = nullptr;
pthread_t thread;
JavaVM *global_jvm;
#define LOGV(fmt, ...) DLOG(YVERBOSE, "%s %s (line: %d) " fmt"\033[0m ", __FILE__,__FUNCTION__,__LINE__, ##__VA_ARGS__)
#define LOGD(fmt, ...) DLOG(YDEBUG, "%s %s (line: %d) " fmt"\033[0m ", __FILE__,__FUNCTION__,__LINE__, ##__VA_ARGS__)
#define LOGI(fmt, ...) DLOG(YINFO, "%s %s (line: %d) " fmt"\033[0m ", __FILE__,__FUNCTION__,__LINE__, ##__VA_ARGS__)
#define LOGW(fmt, ...) DLOG(YWARN, "%s %s (line: %d) " fmt"\033[0m ", __FILE__,__FUNCTION__,__LINE__, ##__VA_ARGS__)
#define LOGE(fmt, ...) DLOG(YERROR, "%s %s (line: %d) " fmt"\033[0m ", __FILE__,__FUNCTION__,__LINE__, ##__VA_ARGS__)
JNIEnv *get_env(int *attach) {
if (global_jvm == NULL) return NULL;
*attach = 0;
JNIEnv *jni_env = NULL;
int status = global_jvm->GetEnv((void **)&jni_env, JNI_VERSION_1_6);
if (status == JNI_EDETACHED || jni_env == NULL) {
status = global_jvm->AttachCurrentThread(&jni_env, NULL);
if (status < 0) {
jni_env = NULL;
} else {
*attach = 1;
}
}
return jni_env;
}
void del_env() {
global_jvm->DetachCurrentThread();
}
void * run(void * ch){
int attach = 0;
JNIEnv *env = get_env(&attach);
//jclass cls = env->FindClass("com/example/myapplication/MainActivity");
env->CallVoidMethod(g_MainActivity, methodId);
return 0;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved){
JNIEnv* env = NULL;
jint result = JNI_ERR;
global_jvm = vm;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
return result;
}
myclass = env->FindClass("com/example/myapplication/MainActivity");
methodId =env->GetMethodID(myclass, "showFrame", "()V");
return JNI_VERSION_1_4;
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
JNIEnv* env,
jobject caller/* this */) {
pthread_t pthread;
std::string hello = "Hello from C++";
jstring str= env->NewStringUTF(hello.c_str());
g_MainActivity = env->NewGlobalRef(caller);
pthread_create(&pthread,NULL,run,NULL);
pthread_detach(thread);
return str;
//return env->NewStringUTF(hello.c_str());
}