• 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 androidx.core.os.asOutcomeReceiver
22 import com.android.healthconnect.controller.service.IoDispatcher
23 import com.android.healthconnect.controller.shared.usecase.BaseUseCase
24 import com.android.healthconnect.controller.shared.usecase.UseCaseResults
25 import com.android.healthconnect.controller.utils.TimeSource
26 import java.time.Duration
27 import java.time.Instant
28 import javax.inject.Inject
29 import javax.inject.Singleton
30 import kotlinx.coroutines.CoroutineDispatcher
31 import kotlinx.coroutines.suspendCancellableCoroutine
32 
33 @Singleton
34 class LoadRecentAccessUseCase
35 @Inject
36 constructor(
37     private val manager: HealthConnectManager,
38     @IoDispatcher private val dispatcher: CoroutineDispatcher,
39     private val timeSource: TimeSource,
40 ) : ILoadRecentAccessUseCase, BaseUseCase<Unit, List<AccessLog>>(dispatcher) {
41 
42     companion object {
43         private const val TAG = "LoadRecentAccessUseCase"
44     }
45 
46     /** Returns a list of apps that have recently accessed Health Connect */
47     override suspend fun execute(input: Unit): List<AccessLog> {
48         val accessLogs =
49             suspendCancellableCoroutine<List<AccessLog>> { continuation ->
50                 manager.queryAccessLogs(Runnable::run, continuation.asOutcomeReceiver())
51             }
52 
53         val instant24Hours =
54             Instant.ofEpochMilli(timeSource.currentTimeMillis()).minus(Duration.ofDays(1))
55 
56         // only need the last 24 hours of access logs
57         return accessLogs
58             .filter { accessLog -> accessLog.accessTime.isAfter(instant24Hours) }
59             .sortedByDescending { it.accessTime }
60     }
61 }
62 
63 interface ILoadRecentAccessUseCase {
invokenull64     suspend fun invoke(input: Unit): UseCaseResults<List<AccessLog>>
65 
66     suspend fun execute(input: Unit): List<AccessLog>
67 }
68