1 /*
2  *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef WEBRTC_MODULES_UTILITY_INCLUDE_HELPERS_ANDROID_H_
12 #define WEBRTC_MODULES_UTILITY_INCLUDE_HELPERS_ANDROID_H_
13 
14 #include <jni.h>
15 #include <string>
16 
17 // Abort the process if |jni| has a Java exception pending.
18 // TODO(henrika): merge with CHECK_JNI_EXCEPTION() in jni_helpers.h.
19 #define CHECK_EXCEPTION(jni)        \
20   RTC_CHECK(!jni->ExceptionCheck()) \
21       << (jni->ExceptionDescribe(), jni->ExceptionClear(), "")
22 
23 namespace webrtc {
24 
25 // Return a |JNIEnv*| usable on this thread or NULL if this thread is detached.
26 JNIEnv* GetEnv(JavaVM* jvm);
27 
28 // Return a |jlong| that will correctly convert back to |ptr|.  This is needed
29 // because the alternative (of silently passing a 32-bit pointer to a vararg
30 // function expecting a 64-bit param) picks up garbage in the high 32 bits.
31 jlong PointerTojlong(void* ptr);
32 
33 // JNIEnv-helper methods that wraps the API which uses the JNI interface
34 // pointer (JNIEnv*). It allows us to RTC_CHECK success and that no Java
35 // exception is thrown while calling the method.
36 jmethodID GetMethodID(
37     JNIEnv* jni, jclass c, const char* name, const char* signature);
38 
39 jmethodID GetStaticMethodID(
40     JNIEnv* jni, jclass c, const char* name, const char* signature);
41 
42 jclass FindClass(JNIEnv* jni, const char* name);
43 
44 jobject NewGlobalRef(JNIEnv* jni, jobject o);
45 
46 void DeleteGlobalRef(JNIEnv* jni, jobject o);
47 
48 // Return thread ID as a string.
49 std::string GetThreadId();
50 
51 // Return thread ID as string suitable for debug logging.
52 std::string GetThreadInfo();
53 
54 // Attach thread to JVM if necessary and detach at scope end if originally
55 // attached.
56 class AttachThreadScoped {
57  public:
58   explicit AttachThreadScoped(JavaVM* jvm);
59   ~AttachThreadScoped();
60   JNIEnv* env();
61 
62  private:
63   bool attached_;
64   JavaVM* jvm_;
65   JNIEnv* env_;
66 };
67 
68 // Scoped holder for global Java refs.
69 template<class T>  // T is jclass, jobject, jintArray, etc.
70 class ScopedGlobalRef {
71  public:
ScopedGlobalRef(JNIEnv * jni,T obj)72   ScopedGlobalRef(JNIEnv* jni, T obj)
73       : jni_(jni), obj_(static_cast<T>(NewGlobalRef(jni, obj))) {}
~ScopedGlobalRef()74   ~ScopedGlobalRef() {
75     DeleteGlobalRef(jni_, obj_);
76   }
77   T operator*() const {
78     return obj_;
79   }
80  private:
81   JNIEnv* jni_;
82   T obj_;
83 };
84 
85 }  // namespace webrtc
86 
87 #endif  // WEBRTC_MODULES_UTILITY_INCLUDE_HELPERS_ANDROID_H_
88