1 /* 2 * Copyright (C) 2013 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.testing.alarmservice; 18 19 import android.app.AlarmManager; 20 import android.app.PendingIntent; 21 import android.content.Context; 22 import android.content.Intent; 23 import android.os.RemoteException; 24 import android.os.SystemClock; 25 import android.util.Log; 26 27 import com.android.testing.alarmservice.Alarm.Stub; 28 29 public class AlarmImpl extends Stub { 30 31 private static final String LOG_TAG = AlarmImpl.class.getSimpleName(); 32 33 private Context mContext; 34 35 public AlarmImpl(Context context) { 36 super(); 37 mContext = context; 38 } 39 40 @Override 41 public int prepare() throws RemoteException { 42 WakeUpController.getController().getWakeLock().acquire(); 43 Log.d(LOG_TAG, "AlarmService prepared, wake lock acquired"); 44 return 0; 45 } 46 47 @Override 48 public int setAlarmAndWait(long timeoutMills) throws RemoteException { 49 // calculate when device should be waken up 50 long atTime = SystemClock.elapsedRealtime() + timeoutMills; 51 AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); 52 Intent wakupIntent = new Intent(WakeUpCall.WAKEUP_CALL); 53 PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, wakupIntent, 0); 54 // set alarm, which will be delivered in form of the wakeupIntent 55 am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, atTime, pi); 56 Log.d(LOG_TAG, String.format("Alarm set: %d, giving up wake lock", atTime)); 57 Object lock = WakeUpController.getController().getWakeSync(); 58 // release wakelock and wait for the lock to be poked from the broadcast receiver 59 WakeUpController.getController().getWakeLock().release(); 60 // does not really matter if device enters suspend before we start waiting on lock 61 synchronized (lock) { 62 try { 63 lock.wait(); 64 } catch (InterruptedException e) { 65 } 66 } 67 Log.d(LOG_TAG, String.format("Alarm triggered, done waiting")); 68 return 0; 69 } 70 71 @Override 72 public int done() throws RemoteException { 73 WakeUpController.getController().getWakeLock().release(); 74 return 0; 75 } 76 77 } 78