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 android.healthconnect.cts.utils; 18 19 import static android.healthconnect.test.app.TestAppReceiver.ACTION_RESULT_ERROR; 20 import static android.healthconnect.test.app.TestAppReceiver.ACTION_RESULT_SUCCESS; 21 import static android.healthconnect.test.app.TestAppReceiver.EXTRA_RESULT_ERROR_CODE; 22 import static android.healthconnect.test.app.TestAppReceiver.EXTRA_RESULT_ERROR_MESSAGE; 23 24 import android.content.BroadcastReceiver; 25 import android.content.Context; 26 import android.content.Intent; 27 import android.os.Bundle; 28 29 import java.util.concurrent.CountDownLatch; 30 import java.util.concurrent.TimeUnit; 31 32 /** 33 * Receives responses from test apps, e.g. from {@link 34 * android.healthconnect.test.app.TestAppReceiver}. 35 */ 36 public class TestReceiver extends BroadcastReceiver { 37 38 private static CountDownLatch sLatch = new CountDownLatch(1); 39 private static Bundle sResult = null; 40 private static Integer sErrorCode = null; 41 private static String sErrorMessage = null; 42 getResult()43 public static Bundle getResult() { 44 await(); 45 return sResult; 46 } 47 getErrorCode()48 public static Integer getErrorCode() { 49 await(); 50 return sErrorCode; 51 } 52 getErrorMessage()53 public static String getErrorMessage() { 54 await(); 55 return sErrorMessage; 56 } 57 await()58 private static void await() { 59 try { 60 if (!sLatch.await(10, TimeUnit.SECONDS)) { 61 throw new RuntimeException("Timeout waiting for response"); 62 } 63 } catch (InterruptedException e) { 64 throw new RuntimeException(e); 65 } 66 } 67 reset()68 public static void reset() { 69 sResult = null; 70 sErrorCode = null; 71 sErrorMessage = null; 72 sLatch = new CountDownLatch(1); 73 } 74 75 @Override onReceive(Context context, Intent intent)76 public void onReceive(Context context, Intent intent) { 77 switch (intent.getAction()) { 78 case ACTION_RESULT_SUCCESS: 79 sResult = intent.getExtras(); 80 sLatch.countDown(); 81 break; 82 case ACTION_RESULT_ERROR: 83 sErrorCode = intent.getIntExtra(EXTRA_RESULT_ERROR_CODE, 0); 84 sErrorMessage = intent.getStringExtra(EXTRA_RESULT_ERROR_MESSAGE); 85 sLatch.countDown(); 86 break; 87 default: 88 throw new IllegalStateException("Unsupported action: " + intent.getAction()); 89 } 90 } 91 } 92