2 * //******************************************************************
4 * // Copyright 2015 Intel Corporation.
6 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
8 * // Licensed under the Apache License, Version 2.0 (the "License");
9 * // you may not use this file except in compliance with the License.
10 * // You may obtain a copy of the License at
12 * // http://www.apache.org/licenses/LICENSE-2.0
14 * // Unless required by applicable law or agreed to in writing, software
15 * // distributed under the License is distributed on an "AS IS" BASIS,
16 * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * // See the License for the specific language governing permissions and
18 * // limitations under the License.
20 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 #include "JniOcStack.h"
26 #ifndef _JniListenerManager
27 #define _JniListenerManager
32 class JniListenerManager
35 T* addListener(JNIEnv* env, jobject jListener, RemoveListenerCallback removeListener)
37 T *onEventListener = nullptr;
41 for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
43 if (env->IsSameObject(jListener, it->first))
45 auto refPair = it->second;
46 onEventListener = refPair.first;
49 m_listenerMap.insert(*it);
50 LOGD("OnEventListener: ref. count is incremented");
57 onEventListener = new T(env, jListener, removeListener);
58 jobject jgListener = env->NewGlobalRef(jListener);
64 std::pair<T*, int>>(jgListener, std::pair<T*, int>(onEventListener, 1)));
68 LOGD("OnEventListener: Failed to create global listener ref.");
69 delete onEventListener;
73 LOGD("OnEventListener: new listener");
77 return onEventListener;
80 void removeListener(JNIEnv* env, jobject jListener)
83 for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
85 if (env->IsSameObject(jListener, it->first))
87 auto refPair = it->second;
88 if (refPair.second > 1)
92 m_listenerMap.insert(*it);
93 LOGI("OnEventListener: ref. count is decremented");
97 env->DeleteGlobalRef(it->first);
98 T* listener = refPair.first;
100 m_listenerMap.erase(it);
101 LOGI("OnEventListener is removed");
109 void removeAllListeners(JNIEnv* env)
112 LOGI("All listeners are removed");
114 for (auto& pair : m_listenerMap)
116 env->DeleteGlobalRef(pair.first);
117 auto refPair = pair.second;
118 delete refPair.first;
120 m_listenerMap.clear();
126 std::map<jobject, std::pair<T*, int>> m_listenerMap;
127 std::mutex m_mapMutex;