1 /*
2  * Copyright (C) 2023 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 package android.storageaccess.cts
17 
18 import android.app.Activity
19 import android.content.Intent
20 import android.os.Bundle
21 import android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
22 import android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
23 import android.view.WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
24 import java.util.concurrent.CompletableFuture
25 
26 
27 class ClientActivity : Activity() {
28     private var pendingActivityResult: Boolean = false
29     private var activityResultFuture: CompletableFuture<Result>? = null
30 
onCreatenull31     override fun onCreate(savedInstanceState: Bundle?) {
32         super.onCreate(savedInstanceState)
33         window.addFlags(FLAG_KEEP_SCREEN_ON or FLAG_TURN_SCREEN_ON or FLAG_DISMISS_KEYGUARD)
34     }
35 
startActivityForFutureResultnull36     fun startActivityForFutureResult(
37             intent: Intent,
38             requestCode: Int,
39             future: CompletableFuture<Result>
40     ) {
41         log("ClientActivity.startActivityFor_Future_Result() " +
42                 "requestCode=$requestCode intent=$intent")
43         super.startActivityForResult(intent, requestCode)
44         activityResultFuture = future
45     }
46 
startActivityForResultnull47     override fun startActivityForResult(intent: Intent?, requestCode: Int, options: Bundle?) {
48         if (pendingActivityResult) {
49             // To avoid silly mistakes let's make sure we do not try to start multiple activities
50             // for result at the same time.
51             error("Cannot startActivityForResult(): already waiting for another result.")
52         }
53         pendingActivityResult = true
54         super.startActivityForResult(intent, requestCode, options)
55     }
56 
onActivityResultnull57     override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
58         val result = Result(requestCode, resultCode, data)
59         log("ClientActivity.onActivityResult(): $result")
60 
61         pendingActivityResult = false
62 
63         activityResultFuture?.apply { complete(result) }
64         activityResultFuture = null
65     }
66 
67     data class Result(val requestCode: Int, val resultCode: Int, val data: Intent?)
68 }