Home | History | Annotate | Download | only in util
      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 import com.android.launcher3.Utilities;
     23 
     24 /**
     25  * Utility class to block execution until the UI looper is idle.
     26  */
     27 public class LooperIdleLock implements MessageQueue.IdleHandler, Runnable {
     28 
     29     private final Object mLock;
     30 
     31     private boolean mIsLocked;
     32 
     33     public LooperIdleLock(Object lock, Looper looper) {
     34         mLock = lock;
     35         mIsLocked = true;
     36         if (Utilities.ATLEAST_MARSHMALLOW) {
     37             looper.getQueue().addIdleHandler(this);
     38         } else {
     39             // Looper.myQueue() only gives the current queue. Move the execution to the UI thread
     40             // so that the IdleHandler is attached to the correct message queue.
     41             new LooperExecutor(looper).execute(this);
     42         }
     43     }
     44 
     45     @Override
     46     public void run() {
     47         Looper.myQueue().addIdleHandler(this);
     48     }
     49 
     50     @Override
     51     public boolean queueIdle() {
     52         synchronized (mLock) {
     53             mIsLocked = false;
     54             mLock.notify();
     55         }
     56         return false;
     57     }
     58 
     59     public boolean awaitLocked(long ms) {
     60         if (mIsLocked) {
     61             try {
     62                 // Just in case mFlushingWorkerThread changes but we aren't woken up,
     63                 // wait no longer than 1sec at a time
     64                 mLock.wait(ms);
     65             } catch (InterruptedException ex) {
     66                 // Ignore
     67             }
     68         }
     69         return mIsLocked;
     70     }
     71 }
     72