• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium 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 "base/android/jni_weak_ref.h"
6 
7 #include "base/android/jni_android.h"
8 #include "base/logging.h"
9 
10 using base::android::AttachCurrentThread;
11 
JavaObjectWeakGlobalRef()12 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef()
13   : obj_(NULL) {
14 }
15 
JavaObjectWeakGlobalRef(const JavaObjectWeakGlobalRef & orig)16 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(
17     const JavaObjectWeakGlobalRef& orig)
18     : obj_(NULL) {
19   Assign(orig);
20 }
21 
JavaObjectWeakGlobalRef(JNIEnv * env,jobject obj)22 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(JNIEnv* env, jobject obj)
23     : obj_(env->NewWeakGlobalRef(obj)) {
24   DCHECK(obj_);
25 }
26 
~JavaObjectWeakGlobalRef()27 JavaObjectWeakGlobalRef::~JavaObjectWeakGlobalRef() {
28   reset();
29 }
30 
operator =(const JavaObjectWeakGlobalRef & rhs)31 void JavaObjectWeakGlobalRef::operator=(const JavaObjectWeakGlobalRef& rhs) {
32   Assign(rhs);
33 }
34 
reset()35 void JavaObjectWeakGlobalRef::reset() {
36   if (obj_) {
37     AttachCurrentThread()->DeleteWeakGlobalRef(obj_);
38     obj_ = NULL;
39   }
40 }
41 
42 base::android::ScopedJavaLocalRef<jobject>
get(JNIEnv * env) const43     JavaObjectWeakGlobalRef::get(JNIEnv* env) const {
44   return GetRealObject(env, obj_);
45 }
46 
GetRealObject(JNIEnv * env,jweak obj)47 base::android::ScopedJavaLocalRef<jobject> GetRealObject(
48     JNIEnv* env, jweak obj) {
49   jobject real = NULL;
50   if (obj) {
51     real = env->NewLocalRef(obj);
52     if (!real)
53       DLOG(ERROR) << "The real object has been deleted!";
54   }
55   return base::android::ScopedJavaLocalRef<jobject>(env, real);
56 }
57 
Assign(const JavaObjectWeakGlobalRef & other)58 void JavaObjectWeakGlobalRef::Assign(const JavaObjectWeakGlobalRef& other) {
59   if (&other == this)
60     return;
61 
62   JNIEnv* env = AttachCurrentThread();
63   if (obj_)
64     env->DeleteWeakGlobalRef(obj_);
65 
66   obj_ = other.obj_ ? env->NewWeakGlobalRef(other.obj_) : NULL;
67 }
68