1 /* 2 * Copyright (C) 2017 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.settings.fuelgauge; 18 19 import android.content.BroadcastReceiver; 20 import android.content.Context; 21 import android.content.Intent; 22 import android.content.IntentFilter; 23 import android.support.annotation.VisibleForTesting; 24 25 import com.android.settings.Utils; 26 27 /** 28 * Use this broadcastReceiver to listen to the battery change, and it will invoke 29 * {@link OnBatteryChangedListener} if any of the following happens: 30 * 31 * 1. Battery level has been changed 32 * 2. Battery status has been changed 33 */ 34 public class BatteryBroadcastReceiver extends BroadcastReceiver { 35 36 interface OnBatteryChangedListener { onBatteryChanged()37 void onBatteryChanged(); 38 } 39 40 @VisibleForTesting 41 String mBatteryLevel; 42 @VisibleForTesting 43 String mBatteryStatus; 44 private OnBatteryChangedListener mBatteryListener; 45 private Context mContext; 46 BatteryBroadcastReceiver(Context context)47 public BatteryBroadcastReceiver(Context context) { 48 mContext = context; 49 } 50 51 @Override onReceive(Context context, Intent intent)52 public void onReceive(Context context, Intent intent) { 53 updateBatteryStatus(intent, false /* forceUpdate */); 54 } 55 setBatteryChangedListener(OnBatteryChangedListener lsn)56 public void setBatteryChangedListener(OnBatteryChangedListener lsn) { 57 mBatteryListener = lsn; 58 } 59 register()60 public void register() { 61 final Intent intent = mContext.registerReceiver(this, 62 new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 63 updateBatteryStatus(intent, true /* forceUpdate */); 64 } 65 unRegister()66 public void unRegister() { 67 mContext.unregisterReceiver(this); 68 } 69 updateBatteryStatus(Intent intent, boolean forceUpdate)70 private void updateBatteryStatus(Intent intent, boolean forceUpdate) { 71 if (intent != null && mBatteryListener != null && Intent.ACTION_BATTERY_CHANGED.equals( 72 intent.getAction())) { 73 String batteryLevel = Utils.getBatteryPercentage(intent); 74 String batteryStatus = Utils.getBatteryStatus( 75 mContext.getResources(), intent); 76 if (forceUpdate || !batteryLevel.equals(mBatteryLevel) || !batteryStatus.equals( 77 mBatteryStatus)) { 78 mBatteryLevel = batteryLevel; 79 mBatteryStatus = batteryStatus; 80 mBatteryListener.onBatteryChanged(); 81 } 82 } 83 } 84 85 }