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 android.app.role.cts;
18 
19 import android.app.Activity;
20 import android.content.Intent;
21 import android.util.Pair;
22 
23 import androidx.annotation.NonNull;
24 import androidx.annotation.Nullable;
25 
26 import java.util.concurrent.CountDownLatch;
27 import java.util.concurrent.TimeUnit;
28 
29 /**
30  * An Activity that can start another Activity and wait for its result.
31  */
32 public class WaitForResultActivity extends Activity {
33 
34     private static final int REQUEST_CODE_WAIT_FOR_RESULT = 1;
35 
36     private CountDownLatch mLatch;
37     private int mResultCode;
38     private Intent mData;
39 
startActivityToWaitForResult(@onNull Intent intent)40     public void startActivityToWaitForResult(@NonNull Intent intent) {
41         mLatch = new CountDownLatch(1);
42         startActivityForResult(intent, REQUEST_CODE_WAIT_FOR_RESULT);
43     }
44 
45     @NonNull
waitForActivityResult(long timeoutMillis)46     public Pair<Integer, Intent> waitForActivityResult(long timeoutMillis)
47             throws InterruptedException {
48         mLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);
49         return new Pair<>(mResultCode, mData);
50     }
51 
52     @Override
onActivityResult(int requestCode, int resultCode, @Nullable Intent data)53     protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
54         if (requestCode == REQUEST_CODE_WAIT_FOR_RESULT) {
55             mResultCode = resultCode;
56             mData = data;
57             mLatch.countDown();
58         } else {
59             super.onActivityResult(requestCode, resultCode, data);
60         }
61     }
62 }
63