2 * //******************************************************************
\r
4 * // Copyright 2015 Intel Corporation.
\r
6 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
\r
8 * // Licensed under the Apache License, Version 2.0 (the "License");
\r
9 * // you may not use this file except in compliance with the License.
\r
10 * // You may obtain a copy of the License at
\r
12 * // http://www.apache.org/licenses/LICENSE-2.0
\r
14 * // Unless required by applicable law or agreed to in writing, software
\r
15 * // distributed under the License is distributed on an "AS IS" BASIS,
\r
16 * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
17 * // See the License for the specific language governing permissions and
\r
18 * // limitations under the License.
\r
20 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
\r
23 #include "JniOcStack.h"
\r
26 #ifndef _JniListenerManager
\r
27 #define _JniListenerManager
\r
29 class JniOcResource;
\r
32 class JniListenerManager
\r
35 T* addListener(JNIEnv* env, jobject jListener, JniOcResource* owner)
\r
37 T *onEventListener = NULL;
\r
41 for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
\r
43 if (env->IsSameObject(jListener, it->first))
\r
45 auto refPair = it->second;
\r
46 onEventListener = refPair.first;
\r
48 it->second = refPair;
\r
49 m_listenerMap.insert(*it);
\r
50 LOGD("OnEventListener: ref. count is incremented");
\r
54 if (!onEventListener)
\r
56 onEventListener = new T(env, jListener, owner);
\r
57 jobject jgListener = env->NewGlobalRef(jListener);
\r
61 m_listenerMap.insert(std::pair<jobject, std::pair<T*, int>>(jgListener, std::pair<T*, int>(onEventListener, 1)));
\r
65 LOGD("OnEventListener: Failed to create global listener ref.");
\r
66 delete onEventListener;
\r
68 LOGD("OnEventListener: new listener");
\r
70 m_mapMutex.unlock();
\r
71 return onEventListener;
\r
74 void removeListener(JNIEnv* env, jobject jListener)
\r
77 for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
\r
79 if (env->IsSameObject(jListener, it->first))
\r
81 auto refPair = it->second;
\r
82 if (refPair.second > 1)
\r
85 it->second = refPair;
\r
86 m_listenerMap.insert(*it);
\r
87 LOGI("OnEventListener: ref. count is decremented");
\r
91 env->DeleteGlobalRef(it->first);
\r
92 T* listener = refPair.first;
\r
94 m_listenerMap.erase(it);
\r
96 LOGI("OnEventListener is removed");
\r
101 m_mapMutex.unlock();
\r
104 void removeAllListeners(JNIEnv* env)
\r
108 for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
\r
110 env->DeleteGlobalRef(it->first);
\r
111 auto refPair = it->second;
\r
112 T* listener = refPair.first;
\r
114 m_listenerMap.erase(it);
\r
117 m_mapMutex.unlock();
\r
121 std::map<jobject, std::pair<T*, int>> m_listenerMap;
\r
122 std::mutex m_mapMutex;
\r