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 17 package com.android.car.frameworkpackagestubs.test; 18 19 import android.app.Activity; 20 import android.app.Instrumentation; 21 import android.content.Context; 22 import android.content.Intent; 23 24 import java.util.concurrent.LinkedBlockingQueue; 25 import java.util.concurrent.TimeUnit; 26 27 /** An helper activity to help test cases to startActivityForResult() and pool the result. */ 28 public final class GetResultActivity extends Activity { 29 private static LinkedBlockingQueue<Result> sResult; 30 31 public static class Result { 32 public final int requestCode; 33 public final int resultCode; 34 public final Intent data; 35 Result(int requestCode, int resultCode, Intent data)36 public Result(int requestCode, int resultCode, Intent data) { 37 this.requestCode = requestCode; 38 this.resultCode = resultCode; 39 this.data = data; 40 } 41 } 42 startActivitySync( Context context, Instrumentation instrumentation)43 public static GetResultActivity startActivitySync( 44 Context context, Instrumentation instrumentation) { 45 Intent getActivityResultIntent = new Intent(context, GetResultActivity.class); 46 getActivityResultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 47 sResult = new LinkedBlockingQueue<>(); 48 return (GetResultActivity) instrumentation.startActivitySync(getActivityResultIntent); 49 } 50 poolResultCode()51 public int poolResultCode() { 52 Result result; 53 try { 54 result = sResult.poll(30, TimeUnit.SECONDS); 55 } catch (InterruptedException e) { 56 throw new RuntimeException(e); 57 } 58 if (result == null) { 59 throw new IllegalStateException("Activity didn't receive a Result in 30 seconds"); 60 } 61 return result.resultCode; 62 } 63 64 @Override onActivityResult(int requestCode, int resultCode, Intent data)65 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 66 try { 67 sResult.offer(new Result(requestCode, resultCode, data), 5, TimeUnit.SECONDS); 68 } catch (InterruptedException e) { 69 throw new RuntimeException(e); 70 } 71 } 72 } 73