1 /*
2  * Copyright (C) 2021 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 android.Manifest;
20 import android.annotation.IntRange;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.RequiresPermission;
24 import android.annotation.SdkConstant;
25 import android.annotation.SystemApi;
26 import android.app.IGameManagerService;
27 import android.app.Service;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.os.Handler;
31 import android.os.IBinder;
32 import android.os.RemoteException;
33 import android.os.ServiceManager;
34 import android.util.Log;
35 
36 import com.android.internal.util.function.pooled.PooledLambda;
37 
38 import java.util.Objects;
39 
40 /**
41  * Top-level service of the game service, which provides support for determining
42  * when a game session should begin. It is always kept running by the system.
43  * Because of this it should be kept as lightweight as possible.
44  *
45  * <p> Instead of requiring permissions for sensitive actions (e.g., starting a new game session),
46  * this class is provided with an {@link IGameServiceController} instance which exposes the
47  * sensitive functionality. This controller is provided by the system server when calling the
48  * {@link IGameService#connected(IGameServiceController)} method exposed by this class. The system
49  * server does so only when creating the bound game service.
50  *
51  * <p>Heavyweight operations (such as showing UI) should be implemented in the
52  * associated {@link GameSessionService} when a game session is taking place. Its
53  * implementation should run in a separate process from the {@link GameService}.
54  *
55  * <p>To extend this class, you must declare the service in your manifest file with
56  * the {@link android.Manifest.permission#BIND_GAME_SERVICE} permission
57  * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:
58  * <pre>
59  * &lt;service android:name=".GameService"
60  *          android:label="&#64;string/service_name"
61  *          android:permission="android.permission.BIND_GAME_SERVICE">
62  *     &lt;intent-filter>
63  *         &lt;action android:name="android.service.games.GameService" />
64  *     &lt;/intent-filter>
65  * &lt;/service>
66  * </pre>
67  *
68  * @hide
69  */
70 @SystemApi
71 public class GameService extends Service {
72     private static final String TAG = "GameService";
73 
74     /**
75      * The {@link Intent} that must be declared as handled by the service.
76      * To be supported, the service must also require the
77      * {@link android.Manifest.permission#BIND_GAME_SERVICE} permission so
78      * that other applications can not abuse it.
79      */
80     @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
81     public static final String ACTION_GAME_SERVICE =
82             "android.service.games.action.GAME_SERVICE";
83 
84     /**
85      * Name under which a GameService component publishes information about itself.
86      * This meta-data should reference an XML resource containing a
87      * <code>&lt;{@link
88      * android.R.styleable#GameService game-session-service}&gt;</code> tag.
89      */
90     public static final String SERVICE_META_DATA = "android.game_service";
91 
92     private IGameServiceController mGameServiceController;
93     private IGameManagerService mGameManagerService;
94     private final IGameService mInterface = new IGameService.Stub() {
95         @Override
96         public void connected(IGameServiceController gameServiceController) {
97             Handler.getMain().executeOrSendMessage(PooledLambda.obtainMessage(
98                     GameService::doOnConnected, GameService.this, gameServiceController));
99         }
100 
101         @Override
102         public void disconnected() {
103             Handler.getMain().executeOrSendMessage(PooledLambda.obtainMessage(
104                     GameService::onDisconnected, GameService.this));
105         }
106 
107         @Override
108         public void gameStarted(GameStartedEvent gameStartedEvent) {
109             Handler.getMain().executeOrSendMessage(PooledLambda.obtainMessage(
110                     GameService::onGameStarted, GameService.this, gameStartedEvent));
111         }
112     };
113 
114     private final IBinder.DeathRecipient mGameManagerServiceDeathRecipient = () -> {
115         Log.w(TAG, "System service binder died. Shutting down");
116 
117         Handler.getMain().executeOrSendMessage(PooledLambda.obtainMessage(
118                 GameService::onDisconnected, GameService.this));
119     };
120 
121     @Override
122     @Nullable
onBind(@ullable Intent intent)123     public final IBinder onBind(@Nullable Intent intent) {
124         if (ACTION_GAME_SERVICE.equals(intent.getAction())) {
125             return mInterface.asBinder();
126         }
127 
128         return null;
129     }
130 
doOnConnected(@onNull IGameServiceController gameServiceController)131     private void doOnConnected(@NonNull IGameServiceController gameServiceController) {
132         mGameManagerService =
133                 IGameManagerService.Stub.asInterface(
134                         ServiceManager.getService(Context.GAME_SERVICE));
135         Objects.requireNonNull(mGameManagerService);
136         try {
137             mGameManagerService.asBinder().linkToDeath(mGameManagerServiceDeathRecipient, 0);
138         } catch (RemoteException e) {
139             Log.w(TAG, "Unable to link to death with system service");
140         }
141 
142         mGameServiceController = gameServiceController;
143         onConnected();
144     }
145 
146     /**
147      * Called during service initialization to indicate that the system is ready
148      * to receive interaction from it. You should generally do initialization here
149      * rather than in {@link #onCreate}.
150      */
onConnected()151     public void onConnected() {}
152 
153     /**
154      * Called during service de-initialization to indicate that the system is shutting the
155      * service down. At this point this service may no longer be the active {@link GameService}.
156      * The service should clean up any resources that it holds at this point.
157      */
onDisconnected()158     public void onDisconnected() {}
159 
160     /**
161      * Called when a game task is started. It is the responsibility of the service to determine what
162      * action to take (e.g., request that a game session be created).
163      *
164      * @param gameStartedEvent Contains information about the game being started.
165      */
onGameStarted(@onNull GameStartedEvent gameStartedEvent)166     public void onGameStarted(@NonNull GameStartedEvent gameStartedEvent) {}
167 
168     /**
169      * Call to create a new game session be created for a game. This method may be called
170      * by a game service following {@link #onGameStarted}, using the task ID provided by the
171      * provided {@link GameStartedEvent} (using {@link GameStartedEvent#getTaskId}).
172      *
173      * If a game session already exists for the game task, this call will be ignored and the
174      * existing session will continue.
175      *
176      * @param taskId The taskId of the game.
177      */
178     @RequiresPermission(Manifest.permission.MANAGE_GAME_ACTIVITY)
createGameSession(@ntRangefrom = 0) int taskId)179     public final void createGameSession(@IntRange(from = 0) int taskId) {
180         if (mGameServiceController == null) {
181             throw new IllegalStateException("Can not call before connected()");
182         }
183 
184         try {
185             mGameServiceController.createGameSession(taskId);
186         } catch (RemoteException e) {
187             Log.e(TAG, "Request for game session failed", e);
188         }
189     }
190 }
191