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 String action = intent.getAction(); 54 if (mBatteryListener != null && Intent.ACTION_BATTERY_CHANGED.equals(action) 55 && updateBatteryStatus(intent)) { 56 mBatteryListener.onBatteryChanged(); 57 } 58 } 59 setBatteryChangedListener(OnBatteryChangedListener lsn)60 public void setBatteryChangedListener(OnBatteryChangedListener lsn) { 61 mBatteryListener = lsn; 62 } 63 register()64 public void register() { 65 mContext.registerReceiver(this, 66 new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 67 } 68 unRegister()69 public void unRegister() { 70 mContext.unregisterReceiver(this); 71 } 72 updateBatteryStatus(Intent intent)73 private boolean updateBatteryStatus(Intent intent) { 74 if (intent != null) { 75 String batteryLevel = Utils.getBatteryPercentage(intent); 76 String batteryStatus = Utils.getBatteryStatus( 77 mContext.getResources(), intent); 78 if (!batteryLevel.equals(mBatteryLevel) || !batteryStatus.equals(mBatteryStatus)) { 79 mBatteryLevel = batteryLevel; 80 mBatteryStatus = batteryStatus; 81 return true; 82 } 83 } 84 return false; 85 } 86 87 }