• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * 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 com.android.healthconnect.controller.recentaccess
18 
19 import android.health.connect.HealthConnectManager
20 import android.health.connect.accesslog.AccessLog
21 import android.util.Log
22 import androidx.core.os.asOutcomeReceiver
23 import com.android.healthconnect.controller.service.IoDispatcher
24 import com.android.healthconnect.controller.utils.SystemTimeSource
25 import java.time.Duration
26 import java.time.Instant
27 import javax.inject.Inject
28 import javax.inject.Singleton
29 import kotlinx.coroutines.CoroutineDispatcher
30 import kotlinx.coroutines.suspendCancellableCoroutine
31 import kotlinx.coroutines.withContext
32 
33 @Singleton
34 class LoadRecentAccessUseCase
35 @Inject
36 constructor(
37     private val manager: HealthConnectManager,
38     @IoDispatcher private val dispatcher: CoroutineDispatcher
39 ) : ILoadRecentAccessUseCase {
40 
41     companion object {
42         private const val TAG = "LoadRecentAccessUseCase"
43     }
44 
45     private val timeSource = SystemTimeSource
46 
47     /** Returns a list of apps that have recently accessed Health Connect */
48     override suspend fun invoke(): List<AccessLog> =
49         withContext(dispatcher) {
50             val accessLogs =
51                 try {
52                     suspendCancellableCoroutine<List<AccessLog>> { continuation ->
53                         manager.queryAccessLogs(Runnable::run, continuation.asOutcomeReceiver())
54                     }
55                 } catch (e: Exception) {
56                     Log.e(TAG, "Load error ", e)
57                     listOf()
58                 }
59 
60             val instant24Hours =
61                 Instant.ofEpochMilli(timeSource.currentTimeMillis()).minus(Duration.ofDays(1))
62 
63             // only need the last 24 hours of access logs
64             accessLogs
65                 .filter { accessLog -> accessLog.accessTime.isAfter(instant24Hours) }
66                 .sortedByDescending { it.accessTime }
67         }
68 }
69 
70 interface ILoadRecentAccessUseCase {
invokenull71     suspend fun invoke(): List<AccessLog>
72 }
73