1 /* 2 * Copyright (C) 2020 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.systemui.car.notification; 18 19 import android.annotation.NonNull; 20 import android.car.Car; 21 import android.car.hardware.power.CarPowerManager; 22 import android.car.hardware.power.CarPowerManager.CarPowerStateListener; 23 import android.os.Handler; 24 import android.os.HandlerExecutor; 25 import android.os.Looper; 26 import android.util.Log; 27 28 import com.android.systemui.car.CarServiceProvider; 29 import com.android.systemui.dagger.SysUISingleton; 30 31 import java.util.concurrent.Executor; 32 33 import javax.inject.Inject; 34 35 /** 36 * Helper class for connecting to the {@link CarPowerManager} and listening for power state changes. 37 */ 38 @SysUISingleton 39 public class PowerManagerHelper { 40 public static final String TAG = "PowerManagerHelper"; 41 42 private final CarServiceProvider mCarServiceProvider; 43 44 private CarPowerManager mCarPowerManager; 45 private CarPowerStateListener mCarPowerStateListener; 46 47 private final CarServiceProvider.CarServiceOnConnectedListener mCarServiceLifecycleListener; 48 49 @Inject PowerManagerHelper(CarServiceProvider carServiceProvider)50 public PowerManagerHelper(CarServiceProvider carServiceProvider) { 51 mCarServiceProvider = carServiceProvider; 52 mCarServiceLifecycleListener = car -> { 53 Log.d(TAG, "Car Service connected"); 54 mCarPowerManager = (CarPowerManager) car.getCarManager(Car.POWER_SERVICE); 55 if (mCarPowerManager != null) { 56 mCarPowerManager.setListener(getMainExecutor(), mCarPowerStateListener); 57 } else { 58 Log.e(TAG, "CarPowerManager service not available"); 59 } 60 }; 61 } 62 63 /** 64 * Sets a {@link CarPowerStateListener}. Should be set before {@link #connectToCarService()}. 65 */ setCarPowerStateListener(@onNull CarPowerStateListener listener)66 public void setCarPowerStateListener(@NonNull CarPowerStateListener listener) { 67 mCarPowerStateListener = listener; 68 } 69 70 /** 71 * Connect to Car service. 72 */ connectToCarService()73 public void connectToCarService() { 74 mCarServiceProvider.addListener(mCarServiceLifecycleListener); 75 } 76 getMainExecutor()77 private static Executor getMainExecutor() { 78 return new HandlerExecutor(new Handler(Looper.getMainLooper())); 79 } 80 } 81