Flutter Engine
scoped_java_ref.cc
Go to the documentation of this file.
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 
16  int failed = env_->PushLocalFrame(kDefaultLocalFrameCapacity);
17  FML_DCHECK(!failed);
18 }
19 
21  : env_(env) {
22  int failed = env_->PushLocalFrame(capacity);
23  FML_DCHECK(!failed);
24 }
25 
27  env_->PopLocalFrame(NULL);
28 }
29 
30 JavaRef<jobject>::JavaRef() : obj_(NULL) {}
31 
32 JavaRef<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 
40 JNIEnv* 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 
54 void 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 
68  if (obj_) {
69  FML_DCHECK(env == AttachCurrentThread()); // Is |env| on correct thread.
70  env->DeleteLocalRef(obj_);
71  obj_ = NULL;
72  }
73 }
74 
76  if (obj_) {
77  AttachCurrentThread()->DeleteGlobalRef(obj_);
78  obj_ = NULL;
79  }
80 }
81 
83  jobject obj = obj_;
84  obj_ = NULL;
85  return obj;
86 }
87 
88 } // namespace jni
89 } // namespace fml
static const int kDefaultLocalFrameCapacity
#define FML_DCHECK(condition)
Definition: logging.h:86
Definition: ascii_trie.cc:9
JNIEnv * AttachCurrentThread()
Definition: jni_util.cc:26