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, JniOcResource* owner)
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");
56 onEventListener = new T(env, jListener, owner);
57 jobject jgListener = env->NewGlobalRef(jListener);
63 std::pair<T*, int>>(jgListener, std::pair<T*, int>(onEventListener, 1)));
67 LOGD("OnEventListener: Failed to create global listener ref.");
68 delete onEventListener;
70 LOGD("OnEventListener: new listener");
73 return onEventListener;
76 void removeListener(JNIEnv* env, jobject jListener)
79 for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
81 if (env->IsSameObject(jListener, it->first))
83 auto refPair = it->second;
84 if (refPair.second > 1)
88 m_listenerMap.insert(*it);
89 LOGI("OnEventListener: ref. count is decremented");
93 env->DeleteGlobalRef(it->first);
94 T* listener = refPair.first;
96 m_listenerMap.erase(it);
98 LOGI("OnEventListener is removed");
106 void removeAllListeners(JNIEnv* env)
110 for (auto& pair : m_listenerMap)
112 env->DeleteGlobalRef(pair.first);
113 auto refPair = pair.second;
114 delete refPair.first;
116 m_listenerMap.clear();
122 std::map<jobject, std::pair<T*, int>> m_listenerMap;
123 std::mutex m_mapMutex;