1 /*
2  * Copyright (C) 2018 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.compatibility.common.util
18 
19 import android.app.Activity
20 import android.content.Intent
21 import java.util.concurrent.CompletableFuture
22 import java.util.concurrent.ConcurrentHashMap
23 import java.util.concurrent.atomic.AtomicInteger
24 
25 /**
26  * An [Activity] that exposes a special [startActivityForResult],
27  * returning future resultCode as a [CompletableFuture]
28  */
29 class FutureResultActivity : Activity() {
30 
31     companion object {
32 
33         /** requestCode -> Future<resultCode> */
34         private val requests = ConcurrentHashMap<Int, CompletableFuture<Int>>()
35         private val nextRequestCode = AtomicInteger(0)
36 
doAndAwaitStartnull37         fun doAndAwaitStart(act: () -> Unit): CompletableFuture<Int> {
38             val requestCode = nextRequestCode.get()
39             act()
40             PollingCheck.waitFor(60_000) {
41                 nextRequestCode.get() >= requestCode + 1
42             }
43             return requests[requestCode]!!
44         }
45     }
46 
onActivityResultnull47     override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
48         requests[requestCode]!!.complete(resultCode)
49     }
50 
startActivityForResultnull51     fun startActivityForResult(intent: Intent): CompletableFuture<Int> {
52         val requestCode = nextRequestCode.getAndIncrement()
53         val future = CompletableFuture<Int>()
54         requests[requestCode] = future
55         startActivityForResult(intent, requestCode)
56         return future
57     }
58 }
59