1 /* 2 * Copyright (C) 2019 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 com.android.launcher3.shadows; 18 19 import static com.android.launcher3.util.Executors.createAndStartNewLooper; 20 21 import static org.robolectric.shadow.api.Shadow.directlyOn; 22 import static org.robolectric.util.ReflectionHelpers.setField; 23 24 import android.os.Handler; 25 26 import androidx.annotation.Nullable; 27 28 import com.android.launcher3.util.LooperExecutor; 29 30 import org.robolectric.annotation.Implementation; 31 import org.robolectric.annotation.Implements; 32 import org.robolectric.annotation.RealObject; 33 34 /** 35 * Shadow for {@link LooperExecutor} to provide reset functionality for static executors. 36 */ 37 @Implements(value = LooperExecutor.class, isInAndroidSdk = false) 38 public class ShadowLooperExecutor { 39 40 @RealObject private LooperExecutor mRealExecutor; 41 42 private Handler mOverriddenHandler; 43 44 @Implementation getHandler()45 protected Handler getHandler() { 46 if (mOverriddenHandler != null) { 47 return mOverriddenHandler; 48 } 49 Handler handler = directlyOn(mRealExecutor, LooperExecutor.class, "getHandler"); 50 Thread thread = handler.getLooper().getThread(); 51 if (!thread.isAlive()) { 52 // Robolectric destroys all loopers at the end of every test. Since Launcher maintains 53 // some static threads, they need to be reinitialized in case they were destroyed. 54 setField(mRealExecutor, "mHandler", 55 new Handler(createAndStartNewLooper(thread.getName()))); 56 } 57 return directlyOn(mRealExecutor, LooperExecutor.class, "getHandler"); 58 } 59 setHandler(@ullable Handler handler)60 public void setHandler(@Nullable Handler handler) { 61 mOverriddenHandler = handler; 62 } 63 } 64