/**************************************************************************** Desc: ****************************************************************************/ RCODE JNIBackupClient::WriteData( const void * pvBuffer, FLMUINT uiBytesToWrite) { RCODE rc = NE_XFLM_OK; JNIEnv * pEnv; jclass Cls; jmethodID MId; jbyteArray jBuff = NULL; void * pvBuff; FLMBOOL bMustDetach = FALSE; if (m_pJvm->GetEnv( (void **)&pEnv, JNI_VERSION_1_2) != JNI_OK) { if (m_pJvm->AttachCurrentThread( (void **)&pEnv, NULL) != 0) { rc = RC_SET( NE_XFLM_FAILURE); goto Exit; } bMustDetach = TRUE; } Cls = pEnv->GetObjectClass( m_jClient); MId = pEnv->GetMethodID( Cls, "WriteData", "([B)I"); flmAssert( MId); if ((jBuff = pEnv->NewByteArray( (jsize)uiBytesToWrite)) == NULL) { rc = RC_SET( NE_XFLM_MEM); goto Exit; } pvBuff = pEnv->GetPrimitiveArrayCritical(jBuff, NULL); f_memcpy(pvBuff, pvBuffer, uiBytesToWrite); pEnv->ReleasePrimitiveArrayCritical( jBuff, pvBuff, 0); if( RC_BAD( rc = (RCODE)pEnv->CallIntMethod( m_jClient, MId, jBuff))) { goto Exit; } Exit: if (jBuff) { pEnv->DeleteLocalRef( jBuff); } if (bMustDetach) { if (m_pJvm->DetachCurrentThread() != 0) { flmAssert( 0); rc = RC_SET( NE_XFLM_FAILURE); } } return( rc); }
JNIAttach::JNIAttach(JNIEnv* env) { if (!ThreadJNI.get()) ThreadJNI.reset(new JNIHandle); if (env) { assert(!ThreadJNI->env || env == ThreadJNI->env); JVM(env); ThreadJNI->env = env; } else if (!ThreadJNI->env) { JavaVM* jvm = JVM(); assert(jvm); if (jvm->GetEnv((void**)&ThreadJNI->env, QI_JNI_MIN_VERSION) != JNI_OK || ThreadJNI->env == 0) { char threadName[] = "qimessaging-thread"; JavaVMAttachArgs args = { JNI_VERSION_1_6, threadName, 0 }; if (JVM()->AttachCurrentThread((envPtr)&ThreadJNI->env, &args) != JNI_OK || ThreadJNI->env == 0) { qiLogError() << "Cannot attach callback thread to Java VM"; throw std::runtime_error("Cannot attach callback thread to Java VM"); } ThreadJNI->attached = true; } } ++ThreadJNI->lockCount; }
void* start_routine(void *args) { ALOGI(">>>>>>>>>>>>>I am in, I am a bad boy!!!!<<<<<<<<<<<<<<"); JNIEnv *jnienv = NULL; JavaVM *javavm = NULL; bool should_detach = false; char *apk_path = NULL; javavm = AndroidRuntime::getJavaVM(); if(javavm != NULL){ javavm->GetEnv((void **)&jnienv, JNI_VERSION_1_4); if(jnienv == NULL){ should_detach = true; javavm->AttachCurrentThread(&jnienv, NULL); } if(jnienv != NULL){ apk_path = find_apk_path(); if(!apk_path){ ALOGE("Could found't apk_path"); goto bails; } const char *dexout_dir = "/data/data/com.tencent.mm/dexout"; int state = 0; if (access(dexout_dir, R_OK | W_OK | X_OK) != 0) { int state = mkdir(dexout_dir, S_IRWXU); if (state) { ALOGE("Could create dexout dir"); goto bails; } } state = load_dex(jnienv, apk_path, dexout_dir, "com.android.testplugin.Entry", "invoke"); if(state != 0){ ALOGE("Load dex error!!"); goto bails; } } } bails: if(apk_path){ free(apk_path); apk_path = NULL; } if(javavm && jnienv && should_detach){ javavm->DetachCurrentThread(); jnienv = NULL; javavm = NULL; } return NULL; }
void hide_ads (void) { // Get the android application's activity. ANativeActivity* activity = gEngine.app->activity; JavaVM* jvm = activity->vm; JNIEnv* env = NULL; DTboolean needs_detach = false; int env_stat = jvm->GetEnv( (void**) &env, JNI_VERSION_1_6); if (env_stat == JNI_EDETACHED) { jvm->AttachCurrentThread(&env, 0); needs_detach = true; } ASSERT(env); jclass c_activity = env->GetObjectClass(activity->clazz); ASSERT(c_activity); jmethodID m_hide_ad_popup = env->GetMethodID(c_activity, "hideAdPopup", "()V"); ASSERT(m_hide_ad_popup); env->CallVoidMethod(activity->clazz, m_hide_ad_popup); if (needs_detach) jvm->DetachCurrentThread(); }
void cacheEnv() { JNIEnv* env = nullptr; JavaVM *jvm = JniHelpers::get()->getJavaVM(); jint ret = jvm->GetEnv((void**)&env, JNI_VERSION_1_4); switch (ret) { case JNI_OK : break; case JNI_EDETACHED : if (jvm->AttachCurrentThread(&env, NULL) < 0) { LOGE("Failed to get the environment using AttachCurrentThread()"); return; } else { break; } case JNI_EVERSION : LOGE("JNI interface version 1.4 not supported"); default: LOGE("Failed to get the environment using GetEnv()"); return; } JniHelpers::get()->setEnv(env); }
static bool set_wake_alarm_callout(uint64_t delay_millis, bool should_wake, alarm_cb cb, void *data) { JNIEnv *env; JavaVM *vm = AndroidRuntime::getJavaVM(); jint status = vm->GetEnv((void **)&env, JNI_VERSION_1_6); if (status != JNI_OK && status != JNI_EDETACHED) { ALOGE("%s unable to get environment for JNI call", __func__); return false; } if (status == JNI_EDETACHED && vm->AttachCurrentThread(&env, &sAttachArgs) != 0) { ALOGE("%s unable to attach thread to VM", __func__); return false; } sAlarmCallback = cb; sAlarmCallbackData = data; jboolean jshould_wake = should_wake ? JNI_TRUE : JNI_FALSE; jboolean ret = env->CallBooleanMethod(sJniAdapterServiceObj, method_setWakeAlarm, (jlong)delay_millis, jshould_wake); if (!ret) { sAlarmCallback = NULL; sAlarmCallbackData = NULL; } if (status == JNI_EDETACHED) { vm->DetachCurrentThread(); } return !!ret; }
/** * Used for user supplied input/output functions. See initDxClass(); */ int dx_uio_write (int fd, char* ptr, unsigned cnt) { JavaVM *vm = jvr_getVM(); JNIEnv *e; int detach = 0; if (vm->GetEnv((void **)&e, JNI_VERSION_1_2) != JNI_OK) { vm->AttachCurrentThread((void**)&e,&attachArgs); detach = 1; } if (e->ExceptionOccurred()) { e->ExceptionDescribe(); e->ExceptionClear(); if (detach) { vm->DetachCurrentThread(); } return 0; } jbyteArray byteArray = e->NewByteArray(cnt); jbyte *bufp = (jbyte*) e->GetByteArrayElements(byteArray,0); memcpy(bufp,ptr,cnt); e->ReleaseByteArrayElements(byteArray,bufp,0); int len = e->CallStaticIntMethod(dx_class, dx_uio_write_method, (jint) fd, byteArray); e->DeleteLocalRef(byteArray); if (detach) { vm->DetachCurrentThread(); } return len; }
static int release_wake_lock_callout(const char *lock_name) { JNIEnv *env; JavaVM *vm = AndroidRuntime::getJavaVM(); jint status = vm->GetEnv((void **)&env, JNI_VERSION_1_6); if (status != JNI_OK && status != JNI_EDETACHED) { ALOGE("%s unable to get environment for JNI call", __func__); return BT_STATUS_FAIL; } if (status == JNI_EDETACHED && vm->AttachCurrentThread(&env, &sAttachArgs) != 0) { ALOGE("%s unable to attach thread to VM", __func__); return BT_STATUS_FAIL; } jboolean ret = JNI_FALSE; jstring lock_name_jni = env->NewStringUTF(lock_name); if (lock_name_jni) { ret = env->CallBooleanMethod(sJniAdapterServiceObj, method_releaseWakeLock, lock_name_jni); env->DeleteLocalRef(lock_name_jni); } else { ALOGE("%s unable to allocate string: %s", __func__, lock_name); } if (status == JNI_EDETACHED) { vm->DetachCurrentThread(); } return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; }
CConnectionInfoBase::EConnectionType CConnectionInfoAndroid::GetConnectionType() { // Acquire a pointer to the current JavaVM JavaVM * jVM = CPlaytomicAndroid::GetJavaVM(); if(jVM == NULL) { return e_disconnected; } jobject activity = CPlaytomicAndroid::GetActivity(); JNIEnv* env = 0; int status = jVM->GetEnv((void **)&env, JNI_VERSION_1_6); bool dettachProcess = false; if(status < 0) { dettachProcess = true; status = jVM->AttachCurrentThread(&env, NULL); if(status < 0) { LOGI("invalid env"); return e_disconnected; } } jclass cls_context = env->FindClass("android/content/Context"); jmethodID sys_service = env->GetMethodID(cls_context, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); jfieldID fid = env->GetStaticFieldID(cls_context, "CONNECTIVITY_SERVICE", "Ljava/lang/String;"); jstring systemstr = (jstring)env->GetStaticObjectField(cls_context, fid); jobject obj_connectManager = env->CallObjectMethod(activity, sys_service,systemstr); jclass cls_env = env->GetObjectClass(obj_connectManager); jmethodID mid_getExtStorage = env->GetMethodID(cls_env, "getActiveNetworkInfo", "()Landroid/net/NetworkInfo;"); jobject obj_netInfo = env->CallObjectMethod(obj_connectManager, mid_getExtStorage); int type = -1; if( obj_netInfo) { jclass cls_netInfo = env->GetObjectClass(obj_netInfo); jmethodID mid_getType = env->GetMethodID(cls_netInfo, "getType", "()I"); type = env->CallIntMethod(obj_netInfo, mid_getType); } LOGI("type : %d", type); switch (type) { case e_wifi: return e_wifi; break; case e_mobile: return e_mobile; break; } return e_disconnected; }
// Display the android virtual keyboard. static void displayKeyboard(android_app* state, bool show) { // The following functions is supposed to show / hide functins from a native activity.. but currently do not work. // ANativeActivity_showSoftInput(state->activity, ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT); // ANativeActivity_hideSoftInput(state->activity, ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY); // Show or hide the keyboard by calling the appropriate Java method through JNI instead. jint result; jint flags = 0; JavaVM* jvm = state->activity->vm; JNIEnv* env; jvm->GetEnv((void **)&env, JNI_VERSION_1_6); jvm->AttachCurrentThread(&env, NULL); if (result == JNI_ERR) { return; } // Retrieves NativeActivity. jobject lNativeActivity = state->activity->clazz; jclass ClassNativeActivity = env->GetObjectClass(lNativeActivity); // Retrieves Context.INPUT_METHOD_SERVICE. jclass ClassContext = env->FindClass("android/content/Context"); jfieldID FieldINPUT_METHOD_SERVICE = env->GetStaticFieldID(ClassContext, "INPUT_METHOD_SERVICE", "Ljava/lang/String;"); jobject INPUT_METHOD_SERVICE = env->GetStaticObjectField(ClassContext, FieldINPUT_METHOD_SERVICE); // Runs getSystemService(Context.INPUT_METHOD_SERVICE). jclass ClassInputMethodManager = env->FindClass("android/view/inputmethod/InputMethodManager"); jmethodID MethodGetSystemService = env->GetMethodID(ClassNativeActivity, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); jobject lInputMethodManager = env->CallObjectMethod(lNativeActivity, MethodGetSystemService, INPUT_METHOD_SERVICE); // Runs getWindow().getDecorView(). jmethodID MethodGetWindow = env->GetMethodID(ClassNativeActivity, "getWindow", "()Landroid/view/Window;"); jobject lWindow = env->CallObjectMethod(lNativeActivity, MethodGetWindow); jclass ClassWindow = env->FindClass("android/view/Window"); jmethodID MethodGetDecorView = env->GetMethodID(ClassWindow, "getDecorView", "()Landroid/view/View;"); jobject lDecorView = env->CallObjectMethod(lWindow, MethodGetDecorView); if (show) { // Runs lInputMethodManager.showSoftInput(...). jmethodID MethodShowSoftInput = env->GetMethodID( ClassInputMethodManager, "showSoftInput", "(Landroid/view/View;I)Z"); jboolean result = env->CallBooleanMethod(lInputMethodManager, MethodShowSoftInput, lDecorView, flags); } else { // Runs lWindow.getViewToken() jclass ClassView = env->FindClass("android/view/View"); jmethodID MethodGetWindowToken = env->GetMethodID(ClassView, "getWindowToken", "()Landroid/os/IBinder;"); jobject lBinder = env->CallObjectMethod(lDecorView, MethodGetWindowToken); // lInputMethodManager.hideSoftInput(...). jmethodID MethodHideSoftInput = env->GetMethodID(ClassInputMethodManager, "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z"); jboolean lRes = env->CallBooleanMethod( lInputMethodManager, MethodHideSoftInput, lBinder, flags); } // Finished with the JVM. jvm->DetachCurrentThread(); }
// On selecting the your music menu item, start the file explore activity for the user to choose a song // on their SD card // // sender [in] - the object that sent the selected event? void MusicSelect::HandleYourMusicPressed(CCObject* sender) { jclass tmpClass; // Prevent a stale local ref bug jobject tmpObject; // Prevent a stale local ref bug SimpleAudioEngine::sharedEngine()->playEffect("SFX/select.wav"); // if we haven't before, retrieve all the JNI data to be able to call java methods if (!m_haveJniData) { JavaVM* jvm = cocos2d::JniHelper::getJavaVM(); if (NULL == jvm) CCLog("Failed to get the JavaVM"); jint ret = jvm->GetEnv((void**)&m_env, JNI_VERSION_1_4); if (ret != JNI_OK) CCLog("Failed to get then JNIEnv"); tmpClass = m_env->FindClass("org/cocos2dx/extbeatanni/ExtremeBeatAnnihilation"); if (!tmpClass) CCLog("Failed to find class ExtremeBeatAnnihilation"); m_extBeatAnniClass = (jclass)m_env->NewGlobalRef(tmpClass); jmethodID getObjectMethod = m_env->GetStaticMethodID(m_extBeatAnniClass, "getObject", "()Ljava/lang/Object;"); if(!getObjectMethod) CCLog("Failed to find method getObject"); tmpObject = m_env->CallStaticObjectMethod(m_extBeatAnniClass, getObjectMethod); if(!tmpObject) CCLog("Failed to get the current instance of the running activity"); m_extBeatAnniInstance = (jobject)m_env->NewGlobalRef(tmpObject); m_startupFileExploreMethod = m_env->GetMethodID(m_extBeatAnniClass, "startupFileExplore", "()V"); if (!m_startupFileExploreMethod) CCLog("Failed to find method startupFileExplore"); m_getSelectedSongMethod = m_env->GetMethodID(m_extBeatAnniClass, "getSelectedSong", "()Ljava/lang/String;"); if (!m_getSelectedSongMethod) CCLog("Failed to find method getSelectedSong"); m_haveJniData = true; } // call the java method within the ExtremeBeatAnnihilation activity that will start up file explore m_env->CallNonvirtualVoidMethod(m_extBeatAnniInstance, m_extBeatAnniClass, m_startupFileExploreMethod); m_choseUserMusic = true; // if song wasn't selected previously, set up the scene to start the game if (!m_songSelected) { m_header->setString("Song selected! Press Play or choose another!"); m_itemPlay->setVisible(true); m_itemPlay->setEnabled(true); m_songSelected = true; } }
void FacebookSharing::facebookShare(const std::string& text, const ShareCallback& callback) { int status; JNIEnv* env; JavaVM* gJavaVM = w2f2::AndroidNDKUtils::getJavaVM(); bool isAttached = false; status = gJavaVM->GetEnv((void**)&env, JNI_VERSION_1_4); if(status < 0) { __android_log_print(ANDROID_LOG_ERROR, "cocos2dx PiratesVSNinjas", "(PIRATES) Failed to get JNI environment, assuming native thread"); status = gJavaVM->AttachCurrentThread(&env, NULL); if (status < 0) { __android_log_print(ANDROID_LOG_ERROR, "cocos2dx PiratesVSNinjas", "(PIRATES) facebookShare: failed to attach current thread"); return; } isAttached = true; } jclass activity_class = env->GetObjectClass(g_activity); if (!activity_class ) { __android_log_print(ANDROID_LOG_ERROR, "cocos2dx PiratesVSNinjas", "(PIRATES) facebookShare: failed to get class reference"); if (isAttached) gJavaVM->DetachCurrentThread(); return; } jmethodID method = env->GetMethodID(activity_class, "facebookShare", "(Ljava/lang/String;)V"); if (!method) { __android_log_print(ANDROID_LOG_ERROR, "cocos2dx PiratesVSNinjas", "(PIRATES) facebookShare: failed to get method ID"); if (isAttached) gJavaVM->DetachCurrentThread(); return; } jstring j_text = env->NewStringUTF(text.c_str()); shareCallback_ = callback; env->CallVoidMethod(g_activity, method, j_text); // ShareCallback share_callback = callback; // // d_->facebookSharing_.description = [NSString stringWithUTF8String:text.c_str()]; // [d_->facebookSharing_ shareWithCompletion:^(BOOL published, NSError *error) { // // share_callback.call(published ? true : false, d_->parseError(error)); // // }]; }
/* * Get the JNIEnv pointer for this thread. * * Returns NULL if the slot wasn't allocated or populated. */ /*static*/ JNIEnv* AndroidRuntime::getJNIEnv() { JNIEnv* env; JavaVM* vm = AndroidRuntime::getJavaVM(); assert(vm != NULL); if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) return NULL; return env; }
JNIEXPORT void Java_io_highfidelity_hifiinterface_InterfaceActivity_nativeOnCreate(JNIEnv* env, jobject obj, jobject instance, jobject asset_mgr) { g_assetManager = AAssetManager_fromJava(env, asset_mgr); qRegisterMetaType<QAndroidJniObject>("QAndroidJniObject"); __interfaceActivity = QAndroidJniObject(instance); auto oldMessageHandler = qInstallMessageHandler(tempMessageHandler); unpackAndroidAssets(); qInstallMessageHandler(oldMessageHandler); JavaVM* jvm; env->GetJavaVM(&jvm); QObject::connect(&AndroidHelper::instance(), &AndroidHelper::androidActivityRequested, [jvm](const QString& a, const bool backToScene, QMap<QString, QString> args) { JNIEnv* myNewEnv; JavaVMAttachArgs jvmArgs; jvmArgs.version = JNI_VERSION_1_6; // choose your JNI version jvmArgs.name = NULL; // you might want to give the java thread a name jvmArgs.group = NULL; // you might want to assign the java thread to a ThreadGroup int attachedHere = 0; // know if detaching at the end is necessary jint res = jvm->GetEnv((void**)&myNewEnv, JNI_VERSION_1_6); // checks if current env needs attaching or it is already attached if (JNI_OK != res) { qDebug() << "[JCRASH] GetEnv env not attached yet, attaching now.."; res = jvm->AttachCurrentThread(reinterpret_cast<JNIEnv **>(&myNewEnv), &jvmArgs); if (JNI_OK != res) { qDebug() << "[JCRASH] Failed to AttachCurrentThread, ErrorCode = " << res; return; } else { attachedHere = 1; } } QAndroidJniObject string = QAndroidJniObject::fromString(a); jboolean jBackToScene = (jboolean) backToScene; jclass hashMapClass = myNewEnv->FindClass("java/util/HashMap"); jmethodID mapClassConstructor = myNewEnv->GetMethodID(hashMapClass, "<init>", "()V"); jobject hashmap = myNewEnv->NewObject(hashMapClass, mapClassConstructor); jmethodID mapClassPut = myNewEnv->GetMethodID(hashMapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); QMap<QString, QString>::iterator i; for (i = args.begin(); i != args.end(); ++i) { QAndroidJniObject jKey = QAndroidJniObject::fromString(i.key()); QAndroidJniObject jValue = QAndroidJniObject::fromString(i.value()); myNewEnv->CallObjectMethod(hashmap, mapClassPut, jKey.object<jstring>(), jValue.object<jstring>()); } __interfaceActivity.callMethod<void>("openAndroidActivity", "(Ljava/lang/String;ZLjava/util/HashMap;)V", string.object<jstring>(), jBackToScene, hashmap); if (attachedHere) { jvm->DetachCurrentThread(); } }); QObject::connect(&AndroidHelper::instance(), &AndroidHelper::hapticFeedbackRequested, [](int duration) { jint iDuration = (jint) duration; __interfaceActivity.callMethod<void>("performHapticFeedback", "(I)V", iDuration); }); }
/** * Used for user supplied input/output functions. See initDxClass(); */ int dx_uio_read (int fd, char* ptr, unsigned cnt) { JavaVM *vm = jvr_getVM(); JNIEnv *e; int detach = 0; if (vm->GetEnv((void **)&e, JNI_VERSION_1_2) != JNI_OK) { vm->AttachCurrentThread((void**)&e,&attachArgs); detach = 1; } if (e->ExceptionOccurred()) { e->ExceptionDescribe(); e->ExceptionClear(); return -1; } jcharArray charArray = (jcharArray) e->CallStaticObjectMethod(dx_class, dx_uio_read_method, (jint) fd, (jint) cnt); if (e->ExceptionOccurred()) { e->ExceptionDescribe(); e->ExceptionClear(); if (detach) { vm->DetachCurrentThread(); } return -1; } if (charArray == NULL) { // EOF if (detach) { vm->DetachCurrentThread(); } return -1; } int buflen = e->GetArrayLength(charArray); if (e->ExceptionOccurred()) { e->ExceptionDescribe(); e->ExceptionClear(); if (detach) { vm->DetachCurrentThread(); } return -1; } if (buflen == 0) { // EOF aka no data if (detach) { vm->DetachCurrentThread(); } return -1; } jchar* bufp = (jchar*) e->GetCharArrayElements(charArray,0); if (e->ExceptionOccurred()) { e->ExceptionDescribe(); e->ExceptionClear(); if (detach) { vm->DetachCurrentThread(); } return -1; } memcpy(ptr,bufp,buflen); e->ReleaseCharArrayElements(charArray, bufp, JNI_ABORT); e->DeleteLocalRef(charArray); if (detach) { vm->DetachCurrentThread(); } return buflen; }
void GetFilePath(char* dest, int maxLength, const char* pFileName) { //jni wtf // Acquire a pointer to the current JavaVM JavaVM * jVM = Playtomic::CPlaytomicAndroid::GetJavaVM(); if(jVM == NULL) { return; } JNIEnv* env = 0; int status = jVM->GetEnv((void **)&env, JNI_VERSION_1_6); bool dettachProcess = false; if(status < 0) { dettachProcess = true; status = jVM->AttachCurrentThread(&env, NULL); if(status < 0) { return; } } jclass cls_env = env->FindClass("android/os/Environment"); jmethodID mid_getExtStorage = env->GetStaticMethodID(cls_env, "getExternalStorageDirectory", "()Ljava/io/File;"); jobject obj_File = env->CallStaticObjectMethod(cls_env, mid_getExtStorage); jclass file = env->FindClass("java/io/File"); jmethodID mid_getPath = env->GetMethodID(file, "getPath", "()Ljava/lang/String;"); jstring obj_Path = (jstring)(env->CallObjectMethod(obj_File, mid_getPath)); const char* path = env->GetStringUTFChars(obj_Path, NULL); std::string fullPath(path); env->ReleaseStringUTFChars(obj_Path, path); fullPath += "/"; fullPath += pFileName; if(fullPath.length() > maxLength) { return; } strcpy( dest, fullPath.c_str()); if(dettachProcess) { jVM->DetachCurrentThread(); } }
static JNIEnv *getJavaEnv() { JavaVM *jvm = __state->activity->vm; JNIEnv *java_env = NULL; jvm->GetEnv((void **)&java_env, JNI_VERSION_1_6); jint res = jvm->AttachCurrentThread(&java_env, NULL); if (res == JNI_ERR) { GP_ERROR("Failed to retrieve JVM environment when entering message pump."); } GP_ASSERT(java_env); return java_env; }
JNIEnv * ofGetJNIEnv(){ JNIEnv *env; JavaVM * vm = ofGetJavaVMPtr(); if(!vm){ ofLogError("ofAppAndroidWindow") << "couldn't get java virtual machine"; return NULL; } if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) { ofLogError("ofAppAndroidWindow") << "couldn't get environment using GetEnv()"; return NULL; } return env; }
JNIEnv * ofGetJNIEnv(){ JNIEnv *env; JavaVM * vm = ofGetJavaVMPtr(); if(!vm){ ofLog(OF_LOG_ERROR,"couldn't get java vm"); return NULL; } if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) { ofLog(OF_LOG_ERROR,"Failed to get the environment using GetEnv()"); return NULL; } return env; }
bool JavascriptJavaBridge::CallInfo::getMethodInfo(void) { m_methodID = 0; m_env = 0; JavaVM* jvm = cocos2d::JniHelper::getJavaVM(); jint ret = jvm->GetEnv((void**)&m_env, JNI_VERSION_1_4); switch (ret) { case JNI_OK: break; case JNI_EDETACHED : if (jvm->AttachCurrentThread(&m_env, NULL) < 0) { LOGD("%s", "Failed to get the environment using AttachCurrentThread()"); m_error = JSJ_ERR_VM_THREAD_DETACHED; return false; } break; case JNI_EVERSION : default : LOGD("%s", "Failed to get the environment using GetEnv()"); m_error = JSJ_ERR_VM_FAILURE; return false; } jstring _jstrClassName = m_env->NewStringUTF(m_className.c_str()); m_classID = (jclass) m_env->CallObjectMethod(cocos2d::JniHelper::classloader, cocos2d::JniHelper::loadclassMethod_methodID, _jstrClassName); if (NULL == m_classID) { LOGD("Classloader failed to find class of %s", m_className.c_str()); } m_env->DeleteLocalRef(_jstrClassName); m_methodID = m_env->GetStaticMethodID(m_classID, m_methodName.c_str(), m_methodSig.c_str()); if (!m_methodID) { m_env->ExceptionClear(); LOGD("Failed to find method id of %s.%s %s", m_className.c_str(), m_methodName.c_str(), m_methodSig.c_str()); m_error = JSJ_ERR_METHOD_NOT_FOUND; return false; } return true; }
QAttachedJNIEnv::QAttachedJNIEnv() { JavaVM *vm = javaVM(); if (vm->GetEnv((void**)&jniEnv, JNI_VERSION_1_6) == JNI_EDETACHED) { if (vm->AttachCurrentThread(&jniEnv, 0) < 0) { jniEnv = 0; return; } } if (!m_refCount.hasLocalData()) m_refCount.setLocalData(1); else m_refCount.setLocalData(m_refCount.localData() + 1); }
void Thread::DetachFromJVM() { if (true == IsMainThread()) return; DAVA::CorePlatformAndroid *core = (DAVA::CorePlatformAndroid *)DAVA::Core::Instance(); DAVA::AndroidSystemDelegate* delegate = core->GetAndroidSystemDelegate(); JavaVM *vm = delegate->GetVM(); JNIEnv *env; if (JNI_OK == vm->GetEnv((void**)&env, JNI_VERSION_1_6)) { if (0 != vm->DetachCurrentThread()) Logger::Error("runtime_error(Could not detach current thread from JNI)"); } }
JNIEnv* CCUtilsAndroid::getJNIEnv() { JavaVM* vm = JniHelper::getJavaVM(); JNIEnv* env = NULL; if(vm) { jint ret = vm->GetEnv((void**) &env, JNI_VERSION_1_4); if (ret != JNI_OK) { jint status = vm->AttachCurrentThread(&env, NULL); if(status < 0) { CCLOGERROR("getJNIEnv: failed to attach current thread"); env = NULL; } } } return env; }
void Thread::AttachToJVM() { if (true == IsMainThread()) return; DAVA::CorePlatformAndroid *core = (DAVA::CorePlatformAndroid *)DAVA::Core::Instance(); DAVA::AndroidSystemDelegate* delegate = core->GetAndroidSystemDelegate(); JavaVM *vm = delegate->GetVM(); JNIEnv *env; if (JNI_EDETACHED == vm->GetEnv((void**)&env, JNI_VERSION_1_6)) { if (vm->AttachCurrentThread(&env, NULL)!=0) Logger::Error("runtime_error(Could not attach current thread to JNI)"); } }
static JNIEnv* getJNIEnv(void) { JavaVM* jvm = cocos2d::JniHelper::getJavaVM(); if (NULL == jvm) { LOGD("Failed to get JNIEnv. JniHelper::getJavaVM() is NULL"); return NULL; } JNIEnv *env = NULL; // get jni environment jint ret = jvm->GetEnv((void**) &env, JNI_VERSION_1_4); switch (ret) { case JNI_OK: // Success! return env; case JNI_EDETACHED: // Thread not attached // TODO : If calling AttachCurrentThread() on a native thread // must call DetachCurrentThread() in future. // see: http://developer.android.com/guide/practices/design/jni.html if (jvm->AttachCurrentThread(&env, NULL) < 0) { LOGD("Failed to get the environment using AttachCurrentThread()"); return NULL; } else { // Success : Attached and obtained JNIEnv! return env; } case JNI_EVERSION: // Cannot recover from this error LOGD("JNI interface version 1.4 not supported"); default: LOGD("Failed to get the environment using GetEnv()"); return NULL; } }
// This is the harder trick: Pull the current state out of mid-air. static unpacker* get_unpacker() { //fprintf(stderr, "get_unpacker()\n"); JavaVM* vm = null; JNI_GetCreatedJavaVMs(&vm, 1, null); void* envRaw = null; vm->GetEnv(&envRaw, JNI_VERSION_1_1); JNIEnv* env = (JNIEnv*) envRaw; //fprintf(stderr, "get_unpacker() env=%p\n", env); if (env == null) return null; jobject pObj = env->CallStaticObjectMethod(NIclazz, currentInstMID); //fprintf(stderr, "get_unpacker() pObj=%p\n", pObj); if (pObj == null) return null; // Got pObj and env; now do it the easy way. return get_unpacker(env, pObj); }
int32_t SpiReadAutoReceiveBufferCallbackStore::performCallback( const char* name, uint32_t* buffer, int32_t numToRead) { JNIEnv* env; JavaVM* vm = sim::GetJVM(); bool didAttachThread = false; int tryGetEnv = vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6); if (tryGetEnv == JNI_EDETACHED) { // Thread not attached didAttachThread = true; if (vm->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr) != 0) { // Failed to attach, log and return wpi::outs() << "Failed to attach\n"; wpi::outs().flush(); return -1; } } else if (tryGetEnv == JNI_EVERSION) { wpi::outs() << "Invalid JVM Version requested\n"; wpi::outs().flush(); } auto toCallbackArr = MakeJIntArray( env, wpi::ArrayRef<uint32_t>{buffer, static_cast<size_t>(numToRead)}); jint ret = env->CallIntMethod(m_call, sim::GetBufferCallback(), MakeJString(env, name), toCallbackArr, (jint)numToRead); jint* fromCallbackArr = reinterpret_cast<jint*>( env->GetPrimitiveArrayCritical(toCallbackArr, nullptr)); for (int i = 0; i < ret; i++) { buffer[i] = fromCallbackArr[i]; } env->ReleasePrimitiveArrayCritical(toCallbackArr, fromCallbackArr, JNI_ABORT); if (env->ExceptionCheck()) { env->ExceptionDescribe(); } if (didAttachThread) { vm->DetachCurrentThread(); } return ret; }
Jvm::Env::Env(bool daemon) : env(NULL), detach(false) { JavaVM* jvm = Jvm::get()->jvm; // First check if we are already attached. int result = jvm->GetEnv(JNIENV_CAST(&env), Jvm::get()->version); // If we're not attached, attach now. if (result == JNI_EDETACHED) { if (daemon) { jvm->AttachCurrentThreadAsDaemon(JNIENV_CAST(&env), NULL); } else { jvm->AttachCurrentThread(JNIENV_CAST(&env), NULL); } detach = true; } }
/** * Used for user supplied input/output functions. See initDxClass(); */ long dx_uio_seek (int fd, long offset, int whence) { JavaVM *vm = jvr_getVM(); JNIEnv *e; int detach = 0; if (vm->GetEnv((void **)&e, JNI_VERSION_1_2) != JNI_OK) { vm->AttachCurrentThread((void**)&e,&attachArgs); detach = 1; } if (e->ExceptionOccurred()) { e->ExceptionDescribe(); e->ExceptionClear(); return -1; } long ret = e->CallStaticLongMethod(dx_class,dx_uio_seek_method,(jint) fd,(jlong) offset,(jint) whence); if (detach) { vm->DetachCurrentThread(); } return ret; }
bool CCLuaJavaBridge::CallInfo::getMethodInfo(void) { m_methodID = 0; m_env = 0; JavaVM* jvm = cocos2d::JniHelper::getJavaVM(); jint ret = jvm->GetEnv((void**)&m_env, JNI_VERSION_1_4); switch (ret) { case JNI_OK: break; case JNI_EDETACHED : if (jvm->AttachCurrentThread(&m_env, NULL) < 0) { LOGD("%s", "Failed to get the environment using AttachCurrentThread()"); m_error = LUAJ_ERR_VM_THREAD_DETACHED; return false; } break; case JNI_EVERSION : default : LOGD("%s", "Failed to get the environment using GetEnv()"); m_error = LUAJ_ERR_VM_FAILURE; return false; } m_classID = m_env->FindClass(m_className.c_str()); m_methodID = m_env->GetStaticMethodID(m_classID, m_methodName.c_str(), m_methodSig.c_str()); if (!m_methodID) { m_env->ExceptionClear(); LOGD("Failed to find method id of %s.%s %s", m_className.c_str(), m_methodName.c_str(), m_methodSig.c_str()); m_error = LUAJ_ERR_METHOD_NOT_FOUND; return false; } return true; }