1 /* 2 * Copyright (C) 2021 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.server.display.utils; 18 19 import android.hardware.Sensor; 20 import android.hardware.SensorManager; 21 import android.text.TextUtils; 22 23 import java.util.List; 24 25 /** 26 * Provides utility methods for dealing with sensors. 27 */ 28 public class SensorUtils { 29 public static final int NO_FALLBACK = 0; 30 31 /** 32 * Finds the specified sensor by type and name using SensorManager. 33 */ findSensor(SensorManager sensorManager, String sensorType, String sensorName, int fallbackType)34 public static Sensor findSensor(SensorManager sensorManager, String sensorType, 35 String sensorName, int fallbackType) { 36 if (sensorManager == null) { 37 return null; 38 } 39 40 if ("".equals(sensorName) && "".equals(sensorType)) { 41 return null; 42 } 43 final boolean isNameSpecified = !TextUtils.isEmpty(sensorName); 44 final boolean isTypeSpecified = !TextUtils.isEmpty(sensorType); 45 if (isNameSpecified || isTypeSpecified) { 46 final List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL); 47 for (Sensor sensor : sensors) { 48 if ((!isNameSpecified || sensorName.equals(sensor.getName())) 49 && (!isTypeSpecified || sensorType.equals(sensor.getStringType()))) { 50 return sensor; 51 } 52 } 53 } 54 if (fallbackType != NO_FALLBACK) { 55 return sensorManager.getDefaultSensor(fallbackType); 56 } 57 58 return null; 59 } 60 61 } 62