1 // Copyright 2014 The Android Open Source Project 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #pragma once 16 17 #include "aemu/base/async/Looper.h" 18 19 namespace android { 20 namespace base { 21 22 // Convenience class used to implement per-thread Looper instances. 23 // This allows one to call ThreadLooper::get() from any place to retrieve 24 // a thread-local Looper instance. 25 class ThreadLooper { 26 public: 27 // Retrieve the current thread's Looper instance. 28 // 29 // If setLooper() was called previously on this thread, return the 30 // corresponding value. Otherwise, on first call, use Looper:create() 31 // and store the new instsance in thread-local storage. Note that this 32 // new instance will be freed automatically when the thread exits. 33 static Looper* get(); 34 35 // Sets the looper for the current thread. Must be called before get() 36 // for the current thread. |looper| is a Looper instance that cannot be 37 // NULL, and will be returned by future calls to get(). 38 // 39 // Note that |looper| will be stored in thread-local storage but will 40 // not be destroyed when the thread exits (unless |own| is true). 41 static void setLooper(Looper* looper, bool own = false); 42 43 // Run the specified std::function on the main loop. 44 using Closure = std::function<void()>; 45 static void runOnMainLooper(Closure&& func); 46 47 // runOnMainLooper(), except waits until |func| finishes, then 48 // returns to the calling thread. 49 // If callled in actual main looper, it will immediately execute func and 50 // return. 51 static void runOnMainLooperAndWaitForCompletion(Closure&& func); 52 53 // Reset the main runner, used by test code when clearing the main looper. 54 static void clearMainRunner(); 55 }; 56 57 } // namespace base 58 } // namespace android 59