Alarm.java revision d3ef3065ab0941567c45e9aec98783138b623c68
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 17package com.android.launcher2; 18 19import android.os.Handler; 20 21public 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 32 public Alarm() { 33 mHandler = new Handler(); 34 } 35 36 public void setOnAlarmListener(OnAlarmListener alarmListener) { 37 mAlarmListener = alarmListener; 38 } 39 40 // Sets the alarm to go off in a certain number of milliseconds. If the alarm is already set, 41 // it's overwritten and only the new alarm setting is used 42 public void setAlarm(long millisecondsInFuture) { 43 long currentTime = System.currentTimeMillis(); 44 mAlarmTriggerTime = currentTime + millisecondsInFuture; 45 if (!mWaitingForCallback) { 46 mHandler.postDelayed(this, mAlarmTriggerTime - currentTime); 47 mWaitingForCallback = true; 48 } 49 } 50 51 public void cancelAlarm() { 52 mAlarmTriggerTime = 0; 53 } 54 55 // this is called when our timer runs out 56 public void run() { 57 mWaitingForCallback = false; 58 if (mAlarmTriggerTime != 0) { 59 long currentTime = System.currentTimeMillis(); 60 if (mAlarmTriggerTime > currentTime) { 61 // We still need to wait some time to trigger spring loaded mode-- 62 // post a new callback 63 mHandler.postDelayed(this, Math.max(0, mAlarmTriggerTime - currentTime)); 64 mWaitingForCallback = true; 65 } else { 66 if (mAlarmListener != null) { 67 mAlarmListener.onAlarm(this); 68 } 69 } 70 } 71 } 72} 73 74interface OnAlarmListener { 75 public void onAlarm(Alarm alarm); 76} 77