一 .引入头文件 (注:不用添加 pthread.h 头文件)
二 . 贴上 C++ 代码
特别注意(pthread_create(&pt, NULL, runMethod, (void*)l); 会报红,不必理会
//当动态库被加载时这个函数被系统调用
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
JNIEnv* env = NULL;
jint result = -1;
//获取JNI版本
if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK)
{
LOGD("GetEnv failed!");
return result;
}
return JNI_VERSION_1_4;
}
void* runMethod(void *args);
extern “C”
JNIEXPORT jint JNICALL
Java_opencv_ucsmy_com_jnithreadapplication_MainActivity_nativeThread(JNIEnv *env,
jobject instance) {
//保存全局JVM以便在子线程中使用
env->GetJavaVM(&g_jvm);
//不能直接赋值(g_obj = obj)
g_obj = env->NewGlobalRef(instance);
int l ;
pthread_t pt ;
//创建子线程
//(pthread_t* _Nonnull, pthread_attr_t const*,void* (* _Nonnull start_routine)(void*), void*);
pthread_create(&pt, NULL, runMethod, (void*)l);
return 1;
}
void* runMethod(void *args) {
JNIEnv *env;
jclass cls;
jmethodID mid;
//Attach主线程
if(g_jvm->AttachCurrentThread(&env,args)!= JNI_OK){
LOGD("%s: AttachCurrentThread() failed", __FUNCTION__);
return NULL;
}
//找到对应的类
cls = env->GetObjectClass(g_obj);
if(cls == NULL){
LOGD("FindClass() Error.....");
return NULL;
}
//(jclass clazz, const char* name, const char* sig)
jmethodID toastID = env->GetMethodID(cls,"showToast","()V");
env->CallVoidMethod(g_obj,toastID);
//Detach主线程
if(g_jvm->DetachCurrentThread() != JNI_OK){
LOGD("%s: DetachCurrentThread() failed", __FUNCTION__);
}
pthread_exit(0);
}
三 ,贴上 Java 代码
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText("zsdtrhfaedrh");
nativeThread();
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native int nativeThread();
public void showToast(){
final String name = "我来自线程--》"+Thread.currentThread().getName();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, name,
Toast.LENGTH_SHORT).show();
}
});
}
}