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 distributed under the
11  * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
12  * KIND, either express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */
15 package com.android.systemui.unfold.system
16 
17 import android.app.ActivityManager
18 import android.app.ActivityManager.RunningTaskInfo
19 import android.app.WindowConfiguration
20 import android.os.Trace
21 import com.android.systemui.shared.system.TaskStackChangeListener
22 import com.android.systemui.shared.system.TaskStackChangeListeners
23 import com.android.systemui.unfold.util.CurrentActivityTypeProvider
24 import javax.inject.Inject
25 import javax.inject.Singleton
26 
27 @Singleton
28 class ActivityManagerActivityTypeProvider
29 @Inject
30 constructor(private val activityManager: ActivityManager) : CurrentActivityTypeProvider {
31 
32     override val isHomeActivity: Boolean?
33         get() = _isHomeActivity
34 
35     private var _isHomeActivity: Boolean? = null
36 
37 
38     override fun init() {
39         _isHomeActivity = activityManager.isOnHomeActivity()
40         TaskStackChangeListeners.getInstance().registerTaskStackListener(taskStackChangeListener)
41     }
42 
43     override fun uninit() {
44         TaskStackChangeListeners.getInstance().unregisterTaskStackListener(taskStackChangeListener)
45     }
46 
47     private val taskStackChangeListener =
48         object : TaskStackChangeListener {
49             override fun onTaskMovedToFront(taskInfo: RunningTaskInfo) {
50                 _isHomeActivity = taskInfo.isHomeActivity()
51             }
52         }
53 
54     private fun RunningTaskInfo.isHomeActivity(): Boolean =
55         topActivityType == WindowConfiguration.ACTIVITY_TYPE_HOME
56 
57     private fun ActivityManager.isOnHomeActivity(): Boolean? {
58         try {
59             Trace.beginSection("isOnHomeActivity")
60             return getRunningTasks(/* maxNum= */ 1)?.firstOrNull()?.isHomeActivity()
61         } finally {
62             Trace.endSection()
63         }
64     }
65 }
66