1 /* 2 * Copyright (C) 2011 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 package android.os; 18 19 import com.android.layoutlib.bridge.android.BridgeContext; 20 import com.android.layoutlib.bridge.impl.RenderAction; 21 import com.android.tools.layoutlib.annotations.LayoutlibDelegate; 22 23 import java.util.ArrayList; 24 import java.util.HashMap; 25 import java.util.List; 26 import java.util.Map; 27 28 /** 29 * Delegate overriding selected methods of android.os.HandlerThread 30 * 31 * Through the layoutlib_create tool, selected methods of Handler have been replaced 32 * by calls to methods of the same name in this delegate class. 33 * 34 * 35 */ 36 public class HandlerThread_Delegate { 37 38 private static final Map<BridgeContext, List<HandlerThread>> sThreads = new HashMap<>(); 39 cleanUp(BridgeContext context)40 public static void cleanUp(BridgeContext context) { 41 List<HandlerThread> list = sThreads.get(context); 42 if (list != null) { 43 for (HandlerThread thread : list) { 44 thread.quit(); 45 } 46 47 list.clear(); 48 sThreads.remove(context); 49 } 50 } 51 52 // -------- Delegate methods 53 54 @LayoutlibDelegate run(HandlerThread theThread)55 /*package*/ static void run(HandlerThread theThread) { 56 // record the thread so that it can be quit() on clean up. 57 BridgeContext context = RenderAction.getCurrentContext(); 58 List<HandlerThread> list = sThreads.computeIfAbsent(context, k -> new ArrayList<>()); 59 list.add(theThread); 60 61 // ---- START DEFAULT IMPLEMENTATION. 62 63 theThread.mTid = Process.myTid(); 64 Looper.prepare(); 65 synchronized (theThread) { 66 theThread.mLooper = Looper.myLooper(); 67 theThread.notifyAll(); 68 } 69 Process.setThreadPriority(theThread.mPriority); 70 theThread.onLooperPrepared(); 71 Looper.loop(); 72 theThread.mTid = -1; 73 } 74 } 75