1 // Copyright 2015 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 "mojo/android/system/base_run_loop.h" 6 7 #include <jni.h> 8 9 #include "base/android/base_jni_registrar.h" 10 #include "base/android/jni_android.h" 11 #include "base/android/jni_registrar.h" 12 #include "base/bind.h" 13 #include "base/logging.h" 14 #include "base/message_loop/message_loop.h" 15 #include "base/run_loop.h" 16 #include "base/single_thread_task_runner.h" 17 #include "jni/BaseRunLoop_jni.h" 18 19 using base::android::JavaParamRef; 20 21 namespace mojo { 22 namespace android { 23 24 static jlong CreateBaseRunLoop(JNIEnv* env, 25 const JavaParamRef<jobject>& jcaller) { 26 base::MessageLoop* message_loop = new base::MessageLoop; 27 return reinterpret_cast<uintptr_t>(message_loop); 28 } 29 30 static void Run(JNIEnv* env, 31 const JavaParamRef<jobject>& jcaller) { 32 base::RunLoop().Run(); 33 } 34 35 static void RunUntilIdle(JNIEnv* env, 36 const JavaParamRef<jobject>& jcaller) { 37 base::RunLoop().RunUntilIdle(); 38 } 39 40 static void Quit(JNIEnv* env, 41 const JavaParamRef<jobject>& jcaller, 42 jlong runLoopID) { 43 reinterpret_cast<base::MessageLoop*>(runLoopID)->QuitWhenIdle(); 44 } 45 46 static void RunJavaRunnable( 47 const base::android::ScopedJavaGlobalRef<jobject>& runnable_ref) { 48 Java_BaseRunLoop_runRunnable(base::android::AttachCurrentThread(), 49 runnable_ref); 50 } 51 52 static void PostDelayedTask(JNIEnv* env, 53 const JavaParamRef<jobject>& jcaller, 54 jlong runLoopID, 55 const JavaParamRef<jobject>& runnable, 56 jlong delay) { 57 base::android::ScopedJavaGlobalRef<jobject> runnable_ref; 58 // ScopedJavaGlobalRef do not hold onto the env reference, so it is safe to 59 // use it across threads. |RunJavaRunnable| will acquire a new JNIEnv before 60 // running the Runnable. 61 runnable_ref.Reset(env, runnable); 62 reinterpret_cast<base::MessageLoop*>(runLoopID) 63 ->task_runner() 64 ->PostDelayedTask(FROM_HERE, base::Bind(&RunJavaRunnable, runnable_ref), 65 base::TimeDelta::FromMicroseconds(delay)); 66 } 67 68 static void DeleteMessageLoop(JNIEnv* env, 69 const JavaParamRef<jobject>& jcaller, 70 jlong runLoopID) { 71 base::MessageLoop* message_loop = 72 reinterpret_cast<base::MessageLoop*>(runLoopID); 73 delete message_loop; 74 } 75 76 bool RegisterBaseRunLoop(JNIEnv* env) { 77 return RegisterNativesImpl(env); 78 } 79 80 } // namespace android 81 } // namespace mojo 82 83