1 /* 2 * Copyright (C) 2021 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 package android.localemanager.cts; 17 18 import android.content.BroadcastReceiver; 19 import android.content.Context; 20 import android.content.Intent; 21 import android.os.LocaleList; 22 23 import org.junit.Assert; 24 25 import java.util.concurrent.CountDownLatch; 26 import java.util.concurrent.TimeUnit; 27 28 /** 29 * Used to dynamically register a receiver in instrumentation test. 30 * 31 * <p>This is used to listen to the following: 32 * <ul> 33 * <li> Broadcasts sent to the current app instrumenting the test. The broadcast is sent by the 34 * service being tested. 35 * <li> Response sent by other apps(TestApp, InstallerApp) to the tests. 36 * </ul> 37 */ 38 public class BlockingBroadcastReceiver extends BroadcastReceiver { 39 private static final String EXTRA_IME_ID = "input_method_id"; 40 41 private CountDownLatch mLatch = new CountDownLatch(1); 42 private String mPackageName; 43 private LocaleList mLocales; 44 private String mInputMethodId; 45 private int mCalls; 46 47 @Override onReceive(Context context, Intent intent)48 public void onReceive(Context context, Intent intent) { 49 if (intent.hasExtra(Intent.EXTRA_PACKAGE_NAME)) { 50 mPackageName = intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME); 51 } 52 if (intent.hasExtra(Intent.EXTRA_LOCALE_LIST)) { 53 mLocales = intent.getParcelableExtra(Intent.EXTRA_LOCALE_LIST); 54 } 55 if (intent.hasExtra(EXTRA_IME_ID)) { 56 mInputMethodId = intent.getStringExtra(EXTRA_IME_ID); 57 } 58 mCalls += 1; 59 mLatch.countDown(); 60 } 61 getPackageName()62 public String getPackageName() { 63 return mPackageName; 64 } 65 getLocales()66 public LocaleList getLocales() { 67 return mLocales; 68 } 69 getInputMethodId()70 public String getInputMethodId() { 71 return mInputMethodId; 72 } 73 await()74 public boolean await() throws Exception { 75 return mLatch.await(5, TimeUnit.SECONDS); 76 } 77 reset()78 public void reset() { 79 mLatch = new CountDownLatch(1); 80 mCalls = 0; 81 mPackageName = null; 82 mLocales = null; 83 mInputMethodId = null; 84 } 85 86 /** 87 * Waits for a while and checks no broadcasts are received. 88 */ assertNoBroadcastReceived()89 public void assertNoBroadcastReceived() throws Exception { 90 await(); 91 Assert.assertEquals(0, mCalls); 92 } 93 } 94