1 /******************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
21 #ifndef RCS_JIN_SCOPEDENV_H_
22 #define RCS_JIN_SCOPEDENV_H_
28 #include "JNIEnvWrapper.h"
35 inline std::pair<JNIEnv*, bool> getEnv()
40 auto ret = g_jvm->GetEnv((void**) &env, JNI_VERSION_1_6);
49 auto attachRet = g_jvm->AttachCurrentThread(&env, NULL);
51 if (attachRet != JNI_OK)
53 LOGT_E("JNI-ScopedEnv", "Failed to get the environment : %d", attachRet);
62 LOGT_E("JNI-ScopedEnv", "JNI version not supported");
66 LOGT_E("JNI-ScopedEnv", "Failed to get the environment");
70 return { env, needToDetach };
77 ScopedEnv() noexcept :
79 m_needToDetach{ false }
81 auto val = Detail::getEnv();
84 m_needToDetach = val.second;
89 if (m_env && m_needToDetach)
91 g_jvm->DetachCurrentThread();
95 ScopedEnv(const ScopedEnv&) = delete;
96 ScopedEnv& operator=(const ScopedEnv&) = delete;
98 operator bool() const noexcept
103 JNIEnv* operator->() noexcept
108 JNIEnv* get() noexcept
118 class ScopedEnvWrapper
121 ScopedEnvWrapper() noexcept :
123 m_needToDetach{ false }
125 auto val = Detail::getEnv();
128 m_needToDetach = val.second;
133 if (m_env && m_needToDetach)
135 g_jvm->DetachCurrentThread();
139 ScopedEnvWrapper(const ScopedEnvWrapper&) = delete;
140 ScopedEnvWrapper& operator=(const ScopedEnvWrapper&) = delete;
142 operator bool() const noexcept
147 JNIEnvWrapper* operator->() noexcept
152 JNIEnvWrapper* get() noexcept
162 #endif // RCS_JIN_SCOPEDENV_H_