summaryrefslogtreecommitdiff
path: root/ClusterHomeSample/src/com/android/car/cluster/home/ClusterHomeApplication.java
blob: c85fa415a6ac226ce4d2aa5b8c7e1b5960222418 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.car.cluster.home;

import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
import static android.car.CarOccupantZoneManager.DISPLAY_TYPE_INSTRUMENT_CLUSTER;
import static android.car.cluster.ClusterHomeManager.ClusterStateListener;
import static android.car.cluster.ClusterHomeManager.UI_TYPE_CLUSTER_HOME;
import static android.car.cluster.ClusterHomeManager.UI_TYPE_CLUSTER_NONE;
import static android.car.user.CarUserManager.USER_LIFECYCLE_EVENT_TYPE_STARTING;
import static android.car.user.CarUserManager.USER_LIFECYCLE_EVENT_TYPE_UNLOCKED;
import static android.content.Intent.ACTION_MAIN;
import static android.hardware.input.InputManager.INJECT_INPUT_EVENT_MODE_ASYNC;

import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.ActivityTaskManager;
import android.app.Application;
import android.app.IActivityTaskManager;
import android.app.TaskInfo;
import android.app.TaskStackListener;
import android.car.Car;
import android.car.CarOccupantZoneManager;
import android.car.cluster.ClusterActivityState;
import android.car.cluster.ClusterHomeManager;
import android.car.cluster.ClusterState;
import android.car.input.CarInputManager;
import android.car.input.CarInputManager.CarInputCaptureCallback;
import android.car.user.CarUserManager;
import android.car.user.CarUserManager.UserLifecycleListener;
import android.car.user.UserLifecycleEventFilter;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Rect;
import android.hardware.input.InputManager;
import android.os.RemoteException;
import android.os.UserHandle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;

import java.util.List;

public final class ClusterHomeApplication extends Application {
    public static final String TAG = "ClusterHome";
    private static final boolean DBG = false;
    private static final int UI_TYPE_HOME = UI_TYPE_CLUSTER_HOME;
    private static final int UI_TYPE_MAPS = UI_TYPE_HOME + 1;
    private static final int UI_TYPE_MUSIC = UI_TYPE_HOME + 2;
    private static final int UI_TYPE_PHONE = UI_TYPE_HOME + 3;
    private static final int UI_TYPE_START = UI_TYPE_MAPS;

    private static final byte HOME_AVAILABILITY = 1;
    private static final byte MAPS_AVAILABILITY = 1;
    private static final byte PHONE_AVAILABILITY = 1;
    private static final byte MUSIC_AVAILABILITY = 1;

    private IActivityTaskManager mAtm;
    private InputManager mInputManager;
    private ClusterHomeManager mHomeManager;
    private CarUserManager mUserManager;
    private CarInputManager mCarInputManager;
    private ClusterState mClusterState;
    private byte mUiAvailability[];
    private int mUserLifeCycleEvent = USER_LIFECYCLE_EVENT_TYPE_STARTING;

    private ComponentName[] mClusterActivities;

    private int mLastLaunchedUiType = UI_TYPE_CLUSTER_NONE;
    private int mLastReportedUiType = UI_TYPE_CLUSTER_NONE;

    @Override
    public void onCreate() {
        super.onCreate();
        mClusterActivities = new ComponentName[] {
                new ComponentName(getApplicationContext(), ClusterHomeActivity.class),
                ComponentName.unflattenFromString(
                        getString(R.string.config_clusterMapActivity)),
                ComponentName.unflattenFromString(
                        getString(R.string.config_clusterMusicActivity)),
                ComponentName.unflattenFromString(
                        getString(R.string.config_clusterPhoneActivity)),
        };
        mAtm = ActivityTaskManager.getService();
        try {
            mAtm.registerTaskStackListener(mTaskStackListener);
        } catch (RemoteException e) {
            Log.e(TAG, "remote exception from AM", e);
        }
        mInputManager = getApplicationContext().getSystemService(InputManager.class);

        Car.createCar(getApplicationContext(), /* handler= */ null,
                Car.CAR_WAIT_TIMEOUT_WAIT_FOREVER,
                (car, ready) -> {
                    if (!ready) return;
                    mHomeManager = (ClusterHomeManager) car.getCarManager(Car.CLUSTER_HOME_SERVICE);
                    mUserManager = (CarUserManager) car.getCarManager(Car.CAR_USER_SERVICE);
                    mCarInputManager = (CarInputManager) car.getCarManager(Car.CAR_INPUT_SERVICE);
                    initClusterHome();
                });
    }

    private void initClusterHome() {
        if (mHomeManager == null) {
            Log.e(TAG, "ClusterHome is null (ClusterHomeService may not be enabled), "
                    + "Stopping ClusterHomeSample.");
            return;
        }
        mHomeManager.registerClusterStateListener(getMainExecutor(),mClusterHomeCalback);
        mClusterState = mHomeManager.getClusterState();
        if (!mClusterState.on) {
            mHomeManager.requestDisplay(UI_TYPE_HOME);
        }
        mUiAvailability = buildUiAvailability();
        mHomeManager.reportState(mClusterState.uiType, UI_TYPE_CLUSTER_NONE, mUiAvailability);
        mHomeManager.registerClusterStateListener(getMainExecutor(), mClusterHomeCalback);

        // Using the filter, only listens to the current user starting or unlocked events.
        UserLifecycleEventFilter filter = new UserLifecycleEventFilter.Builder()
                .addUser(UserHandle.CURRENT)
                .addEventType(USER_LIFECYCLE_EVENT_TYPE_STARTING)
                .addEventType(USER_LIFECYCLE_EVENT_TYPE_UNLOCKED).build();
        mUserManager.addListener(getMainExecutor(), filter, mUserLifecycleListener);

        int r = mCarInputManager.requestInputEventCapture(
                DISPLAY_TYPE_INSTRUMENT_CLUSTER,
                new int[]{CarInputManager.INPUT_TYPE_ALL_INPUTS},
                CarInputManager.CAPTURE_REQ_FLAGS_TAKE_ALL_EVENTS_FOR_DISPLAY,
                mInputCaptureCallback);
        if (r != CarInputManager.INPUT_CAPTURE_RESPONSE_SUCCEEDED) {
            Log.e(TAG, "Failed to capture InputEvent on Cluster: r=" + r);
        }

        if (mClusterState.uiType != UI_TYPE_HOME) {
            startClusterActivity(mClusterState.uiType);
        }
    }

    @Override
    public void onTerminate() {
        mCarInputManager.releaseInputEventCapture(DISPLAY_TYPE_INSTRUMENT_CLUSTER);
        mUserManager.removeListener(mUserLifecycleListener);
        mHomeManager.unregisterClusterStateListener(mClusterHomeCalback);
        try {
            mAtm.unregisterTaskStackListener(mTaskStackListener);
        } catch (RemoteException e) {
            Log.e(TAG, "remote exception from AM", e);
        }
        super.onTerminate();
    }

    private void startClusterActivity(int uiType) {
        // Because ClusterHomeActivity runs as a user 0, so it can run in the locked state.
        if (uiType != UI_TYPE_HOME && mUserLifeCycleEvent != USER_LIFECYCLE_EVENT_TYPE_UNLOCKED) {
            Log.i(TAG, "Ignore to start Activity(" + uiType + ") during user-switching");
            return;
        }
        if (mClusterState == null || mClusterState.displayId == Display.INVALID_DISPLAY) {
            Log.w(TAG, "Cluster display is not ready");
            return;
        }
        mLastLaunchedUiType = uiType;
        ComponentName activity = mClusterActivities[uiType];

        Intent intent = new Intent(ACTION_MAIN).setComponent(activity);
        if (mClusterState.bounds != null && mClusterState.insets != null) {
            Rect unobscured = new Rect(mClusterState.bounds);
            unobscured.inset(mClusterState.insets);
            ClusterActivityState state = ClusterActivityState.create(mClusterState.on, unobscured);
            intent.putExtra(Car.CAR_EXTRA_CLUSTER_ACTIVITY_STATE, state.toBundle());
        }
        ActivityOptions options = ActivityOptions.makeBasic();

        // This sample assumes the Activities in this package are running as the system user,
        // and the other Activities are running as a current user.
        int userId = ActivityManager.getCurrentUser();
        if (getApplicationContext().getPackageName().equals(activity.getPackageName())) {
            userId = UserHandle.USER_SYSTEM;
        }
        mHomeManager.startFixedActivityModeAsUser(intent, options.toBundle(), userId);
    }

    private byte[] buildUiAvailability() {
        // TODO(b/183115088): populate uiAvailability based on the package availability
        return new byte[] {
                HOME_AVAILABILITY, MAPS_AVAILABILITY, PHONE_AVAILABILITY, MUSIC_AVAILABILITY
        };
    }

    private final ClusterStateListener mClusterHomeCalback = new ClusterStateListener() {
        @Override
        public void onClusterStateChanged(
                ClusterState state, @ClusterHomeManager.Config int changes) {
            mClusterState = state;
            // We'll restart Activity when the display bounds or insets are changed, to let Activity
            // redraw itself to fit the changed attributes.
            if ((changes & ClusterHomeManager.CONFIG_DISPLAY_BOUNDS) != 0
                    || (changes & ClusterHomeManager.CONFIG_DISPLAY_INSETS) != 0
                    || ((changes & ClusterHomeManager.CONFIG_UI_TYPE) != 0
                            && mLastLaunchedUiType != state.uiType)) {
                startClusterActivity(state.uiType);
            }
        }
    };

    private final TaskStackListener mTaskStackListener = new TaskStackListener() {
        // onTaskMovedToFront isn't called when Activity-change happens within the same task.
        @Override
        public void onTaskStackChanged()  {
            getMainExecutor().execute(ClusterHomeApplication.this::handleTaskStackChanged);
        }
    };

    private void handleTaskStackChanged() {
        if (mClusterState == null || mClusterState.displayId == Display.INVALID_DISPLAY) {
            return;
        }
        TaskInfo taskInfo;
        try {
             taskInfo = mAtm.getRootTaskInfoOnDisplay(
                    WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_UNDEFINED, mClusterState.displayId);
        } catch (RemoteException e) {
            Log.e(TAG, "remote exception from AM", e);
            return;
        }
        if (taskInfo == null) {
            return;
        }
        int uiType = identifyTopTask(taskInfo);
        if (uiType == UI_TYPE_CLUSTER_NONE) {
            Log.w(TAG, "Unexpected top Activity on Cluster: " + taskInfo.topActivity);
            return;
        }
        if (mLastReportedUiType == uiType) {
            // Don't report the same UI type repeatedly.
            return;
        }
        mLastReportedUiType = uiType;
        mHomeManager.reportState(uiType, UI_TYPE_CLUSTER_NONE, mUiAvailability);
    }

    private int identifyTopTask(TaskInfo taskInfo) {
        for (int i = mClusterActivities.length - 1; i >=0; --i) {
            if (mClusterActivities[i].equals(taskInfo.topActivity)) {
                return i;
            }
        }
        return UI_TYPE_CLUSTER_NONE;
    }

    private final UserLifecycleListener mUserLifecycleListener = (event) -> {
        if (DBG) Log.d(TAG, "UserLifecycleListener.onEvent: event=" + event);

        mUserLifeCycleEvent = event.getEventType();
        if (mUserLifeCycleEvent == USER_LIFECYCLE_EVENT_TYPE_STARTING) {
            startClusterActivity(UI_TYPE_HOME);
        } else if (UI_TYPE_HOME != UI_TYPE_START
                && mUserLifeCycleEvent == USER_LIFECYCLE_EVENT_TYPE_UNLOCKED) {
            startClusterActivity(UI_TYPE_START);
        }
    };

    private final CarInputCaptureCallback mInputCaptureCallback = new CarInputCaptureCallback() {
        @Override
        public void onKeyEvents(@CarOccupantZoneManager.DisplayTypeEnum int targetDisplayType,
                List<KeyEvent> keyEvents) {
            keyEvents.forEach((keyEvent) -> onKeyEvent(keyEvent));
        }
    };

    private void onKeyEvent(KeyEvent keyEvent) {
        if (DBG) Log.d(TAG, "onKeyEvent: " + keyEvent);
        if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MENU) {
            if (keyEvent.getAction() != KeyEvent.ACTION_DOWN) return;
            int nextUiType = (mLastLaunchedUiType + 1) % mUiAvailability.length;
            startClusterActivity(nextUiType);
            return;
        }
        // Use Android InputManager to forward KeyEvent.
        mInputManager.injectInputEvent(keyEvent, INJECT_INPUT_EVENT_MODE_ASYNC);
    }
}