UiHandler.java revision 1ddcf0f2bf44d3c9db89112ef52510d9b2433ac4
1/* 2 * Copyright (C) 2012 Google Inc. 3 * Licensed to The Android Open Source Project. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18package com.android.mail.ui; 19 20import android.app.Activity; 21import android.app.FragmentTransaction; 22import android.os.Handler; 23 24import com.android.mail.utils.LogUtils; 25 26import java.util.concurrent.atomic.AtomicInteger; 27 28/** 29 * A thin wrapper of {@link Handler} to run a callback in UI thread. Any callback posted to this 30 * handler is guarantee to run inside {@link Activity} life cycle. However, it can be dropped if the 31 * {@link Activity} has been stopped. This handler is safe to use with {@link FragmentTransaction}. 32 * 33 * @author phamm 34 */ 35public class UiHandler { 36 private final Handler mHandler = new Handler(); 37 private boolean mEnabled = true; 38 private final static String LOG_TAG = new LogUtils().getLogTag(); 39 40 /** Number of {@link Runnable} in the queue. */ 41 private AtomicInteger mCount = new AtomicInteger(0); 42 43 public void post(final Runnable r) { 44 if (mEnabled) { 45 mCount.incrementAndGet(); 46 mHandler.post(new Runnable() { 47 @Override 48 public void run() { 49 mCount.decrementAndGet(); 50 r.run(); 51 } 52 }); 53 } else { 54 LogUtils.d(LOG_TAG, "UiHandler is disabled in post(). Dropping Runnable."); 55 } 56 } 57 58 public void postDelayed(final Runnable r, long delayMillis) { 59 if (mEnabled) { 60 mCount.incrementAndGet(); 61 mHandler.postDelayed(new Runnable() { 62 @Override 63 public void run() { 64 mCount.decrementAndGet(); 65 r.run(); 66 } 67 }, delayMillis); 68 } else { 69 LogUtils.d(LOG_TAG, "UiHandler is disabled in postDelayed(). Dropping Runnable."); 70 } 71 } 72 73 public void removeCallbacks(Runnable r) { 74 mHandler.removeCallbacks(r); 75 } 76 77 public void setEnabled(boolean enabled) { 78 mEnabled = enabled; 79 if (!mEnabled) { 80 int count = mCount.getAndSet(0); 81 if (count > 0) { 82 LogUtils.e(LOG_TAG, "Disable UiHandler. Dropping %d Runnables.", count); 83 } 84 mHandler.removeCallbacksAndMessages(null); 85 } 86 } 87 88 /** 89 * @return whether the {@link UiHandler} is enabled. It's safe to edit UI if the 90 * {@link UiHandler} is enabled. 91 */ 92 public boolean isEnabled() { 93 return mEnabled; 94 } 95}