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/scoped_java_ref.h" 6 7 #include "base/android/jni_android.h" 8 #include "base/logging.h" 9 10 namespace base { 11 namespace android { 12 JavaRef()13JavaRef<jobject>::JavaRef() : obj_(NULL) {} 14 JavaRef(JNIEnv * env,jobject obj)15JavaRef<jobject>::JavaRef(JNIEnv* env, jobject obj) : obj_(obj) { 16 if (obj) { 17 DCHECK(env && env->GetObjectRefType(obj) == JNILocalRefType); 18 } 19 } 20 ~JavaRef()21JavaRef<jobject>::~JavaRef() { 22 } 23 SetNewLocalRef(JNIEnv * env,jobject obj)24JNIEnv* JavaRef<jobject>::SetNewLocalRef(JNIEnv* env, jobject obj) { 25 if (!env) { 26 env = AttachCurrentThread(); 27 } else { 28 DCHECK_EQ(env, AttachCurrentThread()); // Is |env| on correct thread. 29 } 30 if (obj) 31 obj = env->NewLocalRef(obj); 32 if (obj_) 33 env->DeleteLocalRef(obj_); 34 obj_ = obj; 35 return env; 36 } 37 SetNewGlobalRef(JNIEnv * env,jobject obj)38void JavaRef<jobject>::SetNewGlobalRef(JNIEnv* env, jobject obj) { 39 if (!env) { 40 env = AttachCurrentThread(); 41 } else { 42 DCHECK_EQ(env, AttachCurrentThread()); // Is |env| on correct thread. 43 } 44 if (obj) 45 obj = env->NewGlobalRef(obj); 46 if (obj_) 47 env->DeleteGlobalRef(obj_); 48 obj_ = obj; 49 } 50 ResetLocalRef(JNIEnv * env)51void JavaRef<jobject>::ResetLocalRef(JNIEnv* env) { 52 if (obj_) { 53 DCHECK_EQ(env, AttachCurrentThread()); // Is |env| on correct thread. 54 env->DeleteLocalRef(obj_); 55 obj_ = NULL; 56 } 57 } 58 ResetGlobalRef()59void JavaRef<jobject>::ResetGlobalRef() { 60 if (obj_) { 61 AttachCurrentThread()->DeleteGlobalRef(obj_); 62 obj_ = NULL; 63 } 64 } 65 ReleaseInternal()66jobject JavaRef<jobject>::ReleaseInternal() { 67 jobject obj = obj_; 68 obj_ = NULL; 69 return obj; 70 } 71 72 } // namespace android 73 } // namespace base 74