1 /* 2 * Copyright 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <base/callback.h> 20 #include <base/functional/bind.h> 21 #include <base/location.h> 22 23 #include "btif/include/btif_jni_task.h" 24 25 namespace bluetooth { 26 27 class ModuleJniloop { 28 protected: 29 ModuleJniloop() noexcept = default; 30 virtual ~ModuleJniloop() = default; 31 ModuleJniloop(const ModuleJniloop& mod) = delete; 32 33 // Threadsafe post onto jni loop a function with copyable arguments 34 template <typename Functor, typename... Args> PostFunctionOnJni(Functor && functor,Args &&...args)35 void PostFunctionOnJni(Functor&& functor, Args&&... args) const { 36 do_in_jni_thread(base::BindOnce(std::forward<Functor>(functor), std::forward<Args>(args)...)); 37 } 38 39 // Threadsafe post onto jni loop a method and context with copyable arguments 40 template <typename T, typename Functor, typename... Args> PostMethodOnJni(std::shared_ptr<T> ref,Functor && functor,Args...args)41 void PostMethodOnJni(std::shared_ptr<T> ref, Functor&& functor, Args... args) const { 42 do_in_jni_thread(base::BindOnce( 43 [](std::weak_ptr<T> ref, Functor&& functor, Args&&... args) { 44 if (std::shared_ptr<T> spt = ref.lock()) { 45 base::BindOnce(std::forward<Functor>(functor), spt, std::forward<Args>(args)...).Run(); 46 } 47 }, 48 std::weak_ptr<T>(ref), 49 std::forward<Functor>(functor), 50 std::forward<Args>(args)...)); 51 } 52 }; 53 54 } // namespace bluetooth 55