1 /*
2  * Copyright (C) 2017 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.launcher3.util;
18 
19 import android.os.Looper;
20 import android.os.MessageQueue;
21 
22 /**
23  * Utility class to block execution until the UI looper is idle.
24  */
25 public class LooperIdleLock implements MessageQueue.IdleHandler, Runnable {
26 
27     private final Object mLock;
28 
29     private boolean mIsLocked;
30 
LooperIdleLock(Object lock, Looper looper)31     public LooperIdleLock(Object lock, Looper looper) {
32         mLock = lock;
33         mIsLocked = true;
34         looper.getQueue().addIdleHandler(this);
35     }
36 
37     @Override
run()38     public void run() {
39         Looper.myQueue().addIdleHandler(this);
40     }
41 
42     @Override
queueIdle()43     public boolean queueIdle() {
44         synchronized (mLock) {
45             mIsLocked = false;
46             mLock.notify();
47         }
48         return false;
49     }
50 
awaitLocked(long ms)51     public boolean awaitLocked(long ms) {
52         if (mIsLocked) {
53             try {
54                 // Just in case mFlushingWorkerThread changes but we aren't woken up,
55                 // wait no longer than 1sec at a time
56                 mLock.wait(ms);
57             } catch (InterruptedException ex) {
58                 // Ignore
59             }
60         }
61         return mIsLocked;
62     }
63 }
64