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 17 package com.android.server.devicepolicy; 18 19 import android.content.BroadcastReceiver; 20 import android.content.Context; 21 import android.content.Intent; 22 import android.os.UserHandle; 23 24 import java.util.concurrent.Semaphore; 25 import java.util.concurrent.TimeUnit; 26 27 /** 28 * BroadcastReceiver that listens to {@link Intent#ACTION_USER_UNLOCKED} in order to provide 29 * a blocking wait until the managed profile has been started and unlocked. 30 */ 31 class UserUnlockedBlockingReceiver extends BroadcastReceiver { 32 private static final int WAIT_FOR_USER_UNLOCKED_TIMEOUT_SECONDS = 120; 33 34 private final Semaphore mSemaphore = new Semaphore(0); 35 private final int mUserId; 36 UserUnlockedBlockingReceiver(int userId)37 UserUnlockedBlockingReceiver(int userId) { 38 mUserId = userId; 39 } 40 41 @Override onReceive(Context context, Intent intent)42 public void onReceive(Context context, Intent intent) { 43 if (!Intent.ACTION_USER_UNLOCKED.equals(intent.getAction())) { 44 return; 45 } 46 if (intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL) == mUserId) { 47 mSemaphore.release(); 48 } 49 } 50 waitForUserUnlocked()51 public boolean waitForUserUnlocked() { 52 try { 53 return mSemaphore.tryAcquire( 54 WAIT_FOR_USER_UNLOCKED_TIMEOUT_SECONDS, TimeUnit.SECONDS); 55 } catch (InterruptedException ie) { 56 return false; 57 } 58 } 59 } 60