BatteryBroadcastReceiver.java revision 88b27fdeac1215b26eb84c4a1bc9c2b3a0d25522
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 17package com.android.settings.fuelgauge; 18 19import android.content.BroadcastReceiver; 20import android.content.Context; 21import android.content.Intent; 22import android.content.IntentFilter; 23import android.support.annotation.VisibleForTesting; 24 25import 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 */ 34public class BatteryBroadcastReceiver extends BroadcastReceiver { 35 36 interface OnBatteryChangedListener { 37 void onBatteryChanged(); 38 } 39 40 @VisibleForTesting 41 String mBatteryLevel; 42 @VisibleForTesting 43 String mBatteryStatus; 44 private OnBatteryChangedListener mBatteryListener; 45 private Context mContext; 46 47 public BatteryBroadcastReceiver(Context context) { 48 mContext = context; 49 } 50 51 @Override 52 public void onReceive(Context context, Intent intent) { 53 updateBatteryStatus(intent, false /* forceUpdate */); 54 } 55 56 public void setBatteryChangedListener(OnBatteryChangedListener lsn) { 57 mBatteryListener = lsn; 58 } 59 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 66 public void unRegister() { 67 mContext.unregisterReceiver(this); 68 } 69 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}