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.systemui.util; 18 19 import android.app.AlarmManager; 20 import android.os.Handler; 21 import android.os.SystemClock; 22 23 /** 24 * Schedules a timeout through AlarmManager. Ensures that the timeout is called even when 25 * the device is asleep. 26 */ 27 public class AlarmTimeout implements AlarmManager.OnAlarmListener { 28 29 public static final int MODE_IGNORE_IF_SCHEDULED = 1; 30 public static final int MODE_RESCHEDULE_IF_SCHEDULED = 2; 31 32 private final AlarmManager mAlarmManager; 33 private final AlarmManager.OnAlarmListener mListener; 34 private final String mTag; 35 private final Handler mHandler; 36 private boolean mScheduled; 37 AlarmTimeout(AlarmManager alarmManager, AlarmManager.OnAlarmListener listener, String tag, Handler handler)38 public AlarmTimeout(AlarmManager alarmManager, AlarmManager.OnAlarmListener listener, 39 String tag, Handler handler) { 40 mAlarmManager = alarmManager; 41 mListener = listener; 42 mTag = tag; 43 mHandler = handler; 44 } 45 46 /** 47 * Schedules an alarm in {@code timeout} milliseconds in the future. 48 * 49 * @param timeout How long to wait from now. 50 * @param mode {@link #MODE_IGNORE_IF_SCHEDULED} or {@link #MODE_RESCHEDULE_IF_SCHEDULED}. 51 * @return {@code true} when scheduled successfully, {@code false} otherwise. 52 */ schedule(long timeout, int mode)53 public boolean schedule(long timeout, int mode) { 54 switch (mode) { 55 case MODE_IGNORE_IF_SCHEDULED: 56 if (mScheduled) { 57 return false; 58 } 59 break; 60 case MODE_RESCHEDULE_IF_SCHEDULED: 61 if (mScheduled) { 62 cancel(); 63 } 64 break; 65 default: 66 throw new IllegalArgumentException("Illegal mode: " + mode); 67 } 68 69 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, 70 SystemClock.elapsedRealtime() + timeout, mTag, this, mHandler); 71 mScheduled = true; 72 return true; 73 } 74 isScheduled()75 public boolean isScheduled() { 76 return mScheduled; 77 } 78 cancel()79 public void cancel() { 80 if (mScheduled) { 81 mAlarmManager.cancel(this); 82 mScheduled = false; 83 } 84 } 85 86 @Override onAlarm()87 public void onAlarm() { 88 if (!mScheduled) { 89 // We canceled the alarm, but it still fired. Ignore. 90 return; 91 } 92 mScheduled = false; 93 mListener.onAlarm(); 94 } 95 } 96