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 "content/browser/power_save_blocker_android.h" 6 7 #include "base/android/jni_android.h" 8 #include "base/android/jni_weak_ref.h" 9 #include "base/logging.h" 10 #include "content/browser/power_save_blocker_impl.h" 11 #include "content/public/browser/android/content_view_core.h" 12 #include "content/public/browser/browser_thread.h" 13 #include "jni/PowerSaveBlocker_jni.h" 14 #include "ui/base/android/view_android.h" 15 16 using base::android::AttachCurrentThread; 17 using base::android::ScopedJavaLocalRef; 18 using gfx::NativeView; 19 20 namespace content { 21 22 class PowerSaveBlockerImpl::Delegate 23 : public base::RefCountedThreadSafe<PowerSaveBlockerImpl::Delegate> { 24 public: 25 explicit Delegate(NativeView view_android) { 26 j_view_android_ = JavaObjectWeakGlobalRef( 27 AttachCurrentThread(), view_android->GetJavaObject().obj()); 28 } 29 30 // Does the actual work to apply or remove the desired power save block. 31 void ApplyBlock(); 32 void RemoveBlock(); 33 34 private: 35 friend class base::RefCountedThreadSafe<Delegate>; 36 ~Delegate() {} 37 38 JavaObjectWeakGlobalRef j_view_android_; 39 40 DISALLOW_COPY_AND_ASSIGN(Delegate); 41 }; 42 43 void PowerSaveBlockerImpl::Delegate::ApplyBlock() { 44 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 45 JNIEnv* env = AttachCurrentThread(); 46 ScopedJavaLocalRef<jobject> j_object = j_view_android_.get(env); 47 if (j_object.obj()) 48 Java_PowerSaveBlocker_applyBlock(env, j_object.obj()); 49 } 50 51 void PowerSaveBlockerImpl::Delegate::RemoveBlock() { 52 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 53 JNIEnv* env = AttachCurrentThread(); 54 ScopedJavaLocalRef<jobject> j_object = j_view_android_.get(env); 55 if (j_object.obj()) 56 Java_PowerSaveBlocker_removeBlock(env, j_object.obj()); 57 } 58 59 PowerSaveBlockerImpl::PowerSaveBlockerImpl(PowerSaveBlockerType type, 60 const std::string& reason) { 61 // Don't support kPowerSaveBlockPreventAppSuspension 62 } 63 64 PowerSaveBlockerImpl::~PowerSaveBlockerImpl() { 65 if (delegate_) { 66 BrowserThread::PostTask( 67 BrowserThread::UI, FROM_HERE, 68 base::Bind(&Delegate::RemoveBlock, delegate_)); 69 } 70 } 71 72 void PowerSaveBlockerImpl::InitDisplaySleepBlocker(NativeView view_android) { 73 if (!view_android) 74 return; 75 76 delegate_ = new Delegate(view_android); 77 // This may be called on any thread. 78 BrowserThread::PostTask( 79 BrowserThread::UI, FROM_HERE, 80 base::Bind(&Delegate::ApplyBlock, delegate_)); 81 } 82 83 bool RegisterPowerSaveBlocker(JNIEnv* env) { 84 return RegisterNativesImpl(env); 85 } 86 87 } // namespace content 88