Home | History | Annotate | Download | only in android
      1 // Copyright (c) 2012 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_helper.h"
      6 
      7 #include "base/android/jni_android.h"
      8 #include "base/logging.h"
      9 
     10 using base::android::AttachCurrentThread;
     11 
     12 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef()
     13   : obj_(NULL) {
     14 }
     15 
     16 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(
     17     const JavaObjectWeakGlobalRef& orig)
     18     : obj_(NULL) {
     19   Assign(orig);
     20 }
     21 
     22 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(JNIEnv* env, jobject obj)
     23     : obj_(env->NewWeakGlobalRef(obj)) {
     24   DCHECK(obj_);
     25 }
     26 
     27 JavaObjectWeakGlobalRef::~JavaObjectWeakGlobalRef() {
     28   reset();
     29 }
     30 
     31 void JavaObjectWeakGlobalRef::operator=(const JavaObjectWeakGlobalRef& rhs) {
     32   Assign(rhs);
     33 }
     34 
     35 void JavaObjectWeakGlobalRef::reset() {
     36   if (obj_) {
     37     AttachCurrentThread()->DeleteWeakGlobalRef(obj_);
     38     obj_ = NULL;
     39   }
     40 }
     41 
     42 base::android::ScopedJavaLocalRef<jobject>
     43     JavaObjectWeakGlobalRef::get(JNIEnv* env) const {
     44   return GetRealObject(env, obj_);
     45 }
     46 
     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 
     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