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.os.Bundle; 22 import android.util.Pair; 23 24 import androidx.annotation.NonNull; 25 import androidx.annotation.Nullable; 26 27 import java.util.concurrent.CountDownLatch; 28 import java.util.concurrent.TimeUnit; 29 30 /** 31 * An Activity that can start another Activity and wait for its result. 32 */ 33 public class WaitForResultActivity extends Activity { 34 35 private static final int REQUEST_CODE_WAIT_FOR_RESULT = 1; 36 37 private CountDownLatch mLatch; 38 private int mResultCode; 39 private Intent mData; 40 41 @Override onCreate(@ullable Bundle savedInstanceState)42 protected void onCreate(@Nullable Bundle savedInstanceState) { 43 super.onCreate(savedInstanceState); 44 45 if (savedInstanceState != null) { 46 throw new RuntimeException( 47 "Activity was recreated (perhaps due to a configuration change?) " 48 + "and this activity doesn't currently know how to gracefully handle " 49 + "configuration changes."); 50 } 51 } 52 startActivityToWaitForResult(@onNull Intent intent)53 public void startActivityToWaitForResult(@NonNull Intent intent) { 54 mLatch = new CountDownLatch(1); 55 startActivityForResult(intent, REQUEST_CODE_WAIT_FOR_RESULT); 56 } 57 58 @NonNull waitForActivityResult(long timeoutMillis)59 public Pair<Integer, Intent> waitForActivityResult(long timeoutMillis) 60 throws InterruptedException { 61 mLatch.await(timeoutMillis, TimeUnit.MILLISECONDS); 62 return new Pair<>(mResultCode, mData); 63 } 64 65 @Override onActivityResult(int requestCode, int resultCode, @Nullable Intent data)66 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { 67 if (requestCode == REQUEST_CODE_WAIT_FOR_RESULT) { 68 mResultCode = resultCode; 69 mData = data; 70 mLatch.countDown(); 71 } else { 72 super.onActivityResult(requestCode, resultCode, data); 73 } 74 } 75 } 76