1 /* 2 * Copyright (C) 2010 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; 18 19 import android.os.Handler; 20 21 public class Alarm implements Runnable{ 22 // if we reach this time and the alarm hasn't been cancelled, call the listener 23 private long mAlarmTriggerTime; 24 25 // if we've scheduled a call to run() (ie called mHandler.postDelayed), this variable is true. 26 // We use this to avoid having multiple pending callbacks 27 private boolean mWaitingForCallback; 28 29 private Handler mHandler; 30 private OnAlarmListener mAlarmListener; 31 private boolean mAlarmPending = false; 32 33 public Alarm() { 34 mHandler = new Handler(); 35 } 36 37 public void setOnAlarmListener(OnAlarmListener alarmListener) { 38 mAlarmListener = alarmListener; 39 } 40 41 // Sets the alarm to go off in a certain number of milliseconds. If the alarm is already set, 42 // it's overwritten and only the new alarm setting is used 43 public void setAlarm(long millisecondsInFuture) { 44 long currentTime = System.currentTimeMillis(); 45 mAlarmPending = true; 46 mAlarmTriggerTime = currentTime + millisecondsInFuture; 47 if (!mWaitingForCallback) { 48 mHandler.postDelayed(this, mAlarmTriggerTime - currentTime); 49 mWaitingForCallback = true; 50 } 51 } 52 53 public void cancelAlarm() { 54 mAlarmTriggerTime = 0; 55 mAlarmPending = false; 56 } 57 58 // this is called when our timer runs out 59 public void run() { 60 mWaitingForCallback = false; 61 if (mAlarmTriggerTime != 0) { 62 long currentTime = System.currentTimeMillis(); 63 if (mAlarmTriggerTime > currentTime) { 64 // We still need to wait some time to trigger spring loaded mode-- 65 // post a new callback 66 mHandler.postDelayed(this, Math.max(0, mAlarmTriggerTime - currentTime)); 67 mWaitingForCallback = true; 68 } else { 69 mAlarmPending = false; 70 if (mAlarmListener != null) { 71 mAlarmListener.onAlarm(this); 72 } 73 } 74 } 75 } 76 77 public boolean alarmPending() { 78 return mAlarmPending; 79 } 80 } 81