blob: c1d9ad87eccade4ff626d2b83abe601c6ca69f90 [file] [log] [blame]
Henrik Kjellanderff761fb2015-11-04 08:31:52 +01001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef MODULES_UTILITY_INCLUDE_HELPERS_ANDROID_H_
12#define MODULES_UTILITY_INCLUDE_HELPERS_ANDROID_H_
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010013
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
23namespace webrtc {
24
25// Return a |JNIEnv*| usable on this thread or NULL if this thread is detached.
26JNIEnv* 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.
31jlong 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.
36jmethodID GetMethodID(
37 JNIEnv* jni, jclass c, const char* name, const char* signature);
38
39jmethodID GetStaticMethodID(
40 JNIEnv* jni, jclass c, const char* name, const char* signature);
41
42jclass FindClass(JNIEnv* jni, const char* name);
43
44jobject NewGlobalRef(JNIEnv* jni, jobject o);
45
46void DeleteGlobalRef(JNIEnv* jni, jobject o);
47
48// Return thread ID as a string.
49std::string GetThreadId();
50
51// Return thread ID as string suitable for debug logging.
52std::string GetThreadInfo();
53
54// Attach thread to JVM if necessary and detach at scope end if originally
55// attached.
56class 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.
69template<class T> // T is jclass, jobject, jintArray, etc.
70class ScopedGlobalRef {
71 public:
72 ScopedGlobalRef(JNIEnv* jni, T obj)
73 : jni_(jni), obj_(static_cast<T>(NewGlobalRef(jni, obj))) {}
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020087#endif // MODULES_UTILITY_INCLUDE_HELPERS_ANDROID_H_