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 final boolean isNameSpecified = !TextUtils.isEmpty(sensorName); 37 final boolean isTypeSpecified = !TextUtils.isEmpty(sensorType); 38 if (isNameSpecified || isTypeSpecified) { 39 final List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL); 40 for (Sensor sensor : sensors) { 41 if ((!isNameSpecified || sensorName.equals(sensor.getName())) 42 && (!isTypeSpecified || sensorType.equals(sensor.getStringType()))) { 43 return sensor; 44 } 45 } 46 } 47 if (fallbackType != NO_FALLBACK) { 48 return sensorManager.getDefaultSensor(fallbackType); 49 } 50 51 return null; 52 } 53 54 } 55