1 /* 2 * Copyright (C) 2014 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.internal.policy.impl; 18 19 import android.os.Handler; 20 import android.content.Context; 21 import android.hardware.Sensor; 22 import android.hardware.SensorManager; 23 import android.hardware.TriggerEvent; 24 import android.hardware.TriggerEventListener; 25 26 import java.io.PrintWriter; 27 28 /** 29 * Watches for wake gesture sensor events then invokes the listener. 30 */ 31 public abstract class WakeGestureListener { 32 private static final String TAG = "WakeGestureListener"; 33 34 private final SensorManager mSensorManager; 35 private final Handler mHandler; 36 37 private final Object mLock = new Object(); 38 39 private boolean mTriggerRequested; 40 private Sensor mSensor; 41 42 public WakeGestureListener(Context context, Handler handler) { 43 mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); 44 mHandler = handler; 45 46 mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_WAKE_GESTURE); 47 } 48 49 public abstract void onWakeUp(); 50 51 public boolean isSupported() { 52 synchronized (mLock) { 53 return mSensor != null; 54 } 55 } 56 57 public void requestWakeUpTrigger() { 58 synchronized (mLock) { 59 if (mSensor != null && !mTriggerRequested) { 60 mTriggerRequested = true; 61 mSensorManager.requestTriggerSensor(mListener, mSensor); 62 } 63 } 64 } 65 66 public void cancelWakeUpTrigger() { 67 synchronized (mLock) { 68 if (mSensor != null && mTriggerRequested) { 69 mTriggerRequested = false; 70 mSensorManager.cancelTriggerSensor(mListener, mSensor); 71 } 72 } 73 } 74 75 public void dump(PrintWriter pw, String prefix) { 76 synchronized (mLock) { 77 pw.println(prefix + TAG); 78 prefix += " "; 79 pw.println(prefix + "mTriggerRequested=" + mTriggerRequested); 80 pw.println(prefix + "mSensor=" + mSensor); 81 } 82 } 83 84 private final TriggerEventListener mListener = new TriggerEventListener() { 85 @Override 86 public void onTrigger(TriggerEvent event) { 87 synchronized (mLock) { 88 mTriggerRequested = false; 89 mHandler.post(mWakeUpRunnable); 90 } 91 } 92 }; 93 94 private final Runnable mWakeUpRunnable = new Runnable() { 95 @Override 96 public void run() { 97 onWakeUp(); 98 } 99 }; 100 } 101