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 13 JavaRef<jobject>::JavaRef() : obj_(NULL) {} 14 15 JavaRef<jobject>::JavaRef(JNIEnv* env, jobject obj) : obj_(obj) { 16 if (obj) { 17 DCHECK(env && env->GetObjectRefType(obj) == JNILocalRefType); 18 } 19 } 20 21 JavaRef<jobject>::~JavaRef() { 22 } 23 24 JNIEnv* 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 38 void 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 51 void 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 59 void JavaRef<jobject>::ResetGlobalRef() { 60 if (obj_) { 61 AttachCurrentThread()->DeleteGlobalRef(obj_); 62 obj_ = NULL; 63 } 64 } 65 66 jobject JavaRef<jobject>::ReleaseInternal() { 67 jobject obj = obj_; 68 obj_ = NULL; 69 return obj; 70 } 71 72 } // namespace android 73 } // namespace base 74