1 // Copyright 2013 The Flutter Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "flutter/fml/platform/android/scoped_java_ref.h" 6 7 #include "flutter/fml/logging.h" 8 #include "flutter/fml/platform/android/jni_util.h" 9 10 namespace fml { 11 namespace jni { 12 13 static const int kDefaultLocalFrameCapacity = 16; 14 ScopedJavaLocalFrame(JNIEnv * env)15ScopedJavaLocalFrame::ScopedJavaLocalFrame(JNIEnv* env) : env_(env) { 16 int failed = env_->PushLocalFrame(kDefaultLocalFrameCapacity); 17 FML_DCHECK(!failed); 18 } 19 ScopedJavaLocalFrame(JNIEnv * env,int capacity)20ScopedJavaLocalFrame::ScopedJavaLocalFrame(JNIEnv* env, int capacity) 21 : env_(env) { 22 int failed = env_->PushLocalFrame(capacity); 23 FML_DCHECK(!failed); 24 } 25 ~ScopedJavaLocalFrame()26ScopedJavaLocalFrame::~ScopedJavaLocalFrame() { 27 env_->PopLocalFrame(NULL); 28 } 29 JavaRef()30JavaRef<jobject>::JavaRef() : obj_(NULL) {} 31 JavaRef(JNIEnv * env,jobject obj)32JavaRef<jobject>::JavaRef(JNIEnv* env, jobject obj) : obj_(obj) { 33 if (obj) { 34 FML_DCHECK(env && env->GetObjectRefType(obj) == JNILocalRefType); 35 } 36 } 37 38 JavaRef<jobject>::~JavaRef() = default; 39 SetNewLocalRef(JNIEnv * env,jobject obj)40JNIEnv* JavaRef<jobject>::SetNewLocalRef(JNIEnv* env, jobject obj) { 41 if (!env) { 42 env = AttachCurrentThread(); 43 } else { 44 FML_DCHECK(env == AttachCurrentThread()); // Is |env| on correct thread. 45 } 46 if (obj) 47 obj = env->NewLocalRef(obj); 48 if (obj_) 49 env->DeleteLocalRef(obj_); 50 obj_ = obj; 51 return env; 52 } 53 SetNewGlobalRef(JNIEnv * env,jobject obj)54void JavaRef<jobject>::SetNewGlobalRef(JNIEnv* env, jobject obj) { 55 if (!env) { 56 env = AttachCurrentThread(); 57 } else { 58 FML_DCHECK(env == AttachCurrentThread()); // Is |env| on correct thread. 59 } 60 if (obj) 61 obj = env->NewGlobalRef(obj); 62 if (obj_) 63 env->DeleteGlobalRef(obj_); 64 obj_ = obj; 65 } 66 ResetLocalRef(JNIEnv * env)67void JavaRef<jobject>::ResetLocalRef(JNIEnv* env) { 68 if (obj_) { 69 FML_DCHECK(env == AttachCurrentThread()); // Is |env| on correct thread. 70 env->DeleteLocalRef(obj_); 71 obj_ = NULL; 72 } 73 } 74 ResetGlobalRef()75void JavaRef<jobject>::ResetGlobalRef() { 76 if (obj_) { 77 AttachCurrentThread()->DeleteGlobalRef(obj_); 78 obj_ = NULL; 79 } 80 } 81 ReleaseInternal()82jobject JavaRef<jobject>::ReleaseInternal() { 83 jobject obj = obj_; 84 obj_ = NULL; 85 return obj; 86 } 87 88 } // namespace jni 89 } // namespace fml 90