1 /* 2 * Copyright (C) 2022 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.service.games; 18 19 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; 20 21 import android.Manifest; 22 import android.util.Log; 23 24 import androidx.annotation.GuardedBy; 25 26 import com.google.common.collect.ImmutableList; 27 import com.google.common.collect.ImmutableSet; 28 29 import java.util.Set; 30 31 32 /** 33 * Test implementation of {@link GameService}. 34 */ 35 public final class TestGameService extends GameService { 36 private static final String TAG = "TestGameService"; 37 38 private static final Object sLock = new Object(); 39 @GuardedBy("sLock") 40 private static boolean sIsConnected = false; 41 @GuardedBy("sLock") 42 private static Set<String> sGamePackages = ImmutableSet.of(); 43 44 @Override onConnected()45 public void onConnected() { 46 getInstrumentation().getUiAutomation().adoptShellPermissionIdentity( 47 Manifest.permission.MANAGE_GAME_ACTIVITY); 48 49 synchronized (sLock) { 50 sIsConnected = true; 51 } 52 } 53 54 @Override onDisconnected()55 public void onDisconnected() { 56 synchronized (sLock) { 57 sIsConnected = false; 58 } 59 60 try { 61 getInstrumentation().getUiAutomation().dropShellPermissionIdentity(); 62 } catch (IllegalStateException | SecurityException e) { 63 Log.w(TAG, "Failed to drop shell permission identity", e); 64 } 65 } 66 67 @Override onGameStarted(GameStartedEvent gameStartedEvent)68 public void onGameStarted(GameStartedEvent gameStartedEvent) { 69 boolean isGame; 70 synchronized (sLock) { 71 isGame = sGamePackages.contains(gameStartedEvent.getPackageName()); 72 } 73 if (isGame) { 74 createGameSession(gameStartedEvent.getTaskId()); 75 } 76 } 77 reset()78 static void reset() { 79 synchronized (sLock) { 80 sIsConnected = false; 81 } 82 setGamePackages(ImmutableList.of()); 83 } 84 isConnected()85 static boolean isConnected() { 86 synchronized (sLock) { 87 return sIsConnected; 88 } 89 } 90 setGamePackages(Iterable<String> gamePackages)91 static void setGamePackages(Iterable<String> gamePackages) { 92 synchronized (sLock) { 93 sGamePackages = ImmutableSet.copyOf(gamePackages); 94 } 95 } 96 } 97 98