1/*
2 * Copyright (C) 2016 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.incallui.answerproximitysensor;
18
19import android.content.Context;
20import android.hardware.Sensor;
21import android.hardware.SensorEvent;
22import android.hardware.SensorEventListener;
23import android.hardware.SensorManager;
24import android.support.annotation.Nullable;
25import com.android.dialer.common.LogUtil;
26
27/**
28 * A fake PROXIMITY_SCREEN_OFF_WAKE_LOCK implemented by the app. It will use {@link
29 * PseudoScreenState} to fake a black screen when the proximity sensor is near.
30 */
31public class PseudoProximityWakeLock implements AnswerProximityWakeLock, SensorEventListener {
32
33  private final Context context;
34  private final PseudoScreenState pseudoScreenState;
35  private final Sensor proximitySensor;
36
37  @Nullable private ScreenOnListener listener;
38  private boolean isHeld;
39
40  public PseudoProximityWakeLock(Context context, PseudoScreenState pseudoScreenState) {
41    this.context = context;
42    this.pseudoScreenState = pseudoScreenState;
43    pseudoScreenState.setOn(true);
44    proximitySensor =
45        context.getSystemService(SensorManager.class).getDefaultSensor(Sensor.TYPE_PROXIMITY);
46  }
47
48  @Override
49  public void acquire() {
50    isHeld = true;
51    context
52        .getSystemService(SensorManager.class)
53        .registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
54  }
55
56  @Override
57  public void release() {
58    isHeld = false;
59    context.getSystemService(SensorManager.class).unregisterListener(this);
60    pseudoScreenState.setOn(true);
61  }
62
63  @Override
64  public boolean isHeld() {
65    return isHeld;
66  }
67
68  @Override
69  public void setScreenOnListener(ScreenOnListener listener) {
70    this.listener = listener;
71  }
72
73  @Override
74  public void onSensorChanged(SensorEvent sensorEvent) {
75    boolean near = sensorEvent.values[0] < sensorEvent.sensor.getMaximumRange();
76    LogUtil.i("AnswerProximitySensor.PseudoProximityWakeLock.onSensorChanged", "near: " + near);
77    pseudoScreenState.setOn(!near);
78    if (!near && listener != null) {
79      listener.onScreenOn();
80    }
81  }
82
83  @Override
84  public void onAccuracyChanged(Sensor sensor, int i) {}
85}
86