1 /* 2 * Copyright (C) 2010 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.statusbar.policy; 18 19 import android.content.BroadcastReceiver; 20 import android.content.Context; 21 import android.content.Intent; 22 import android.content.IntentFilter; 23 import android.os.BatteryManager; 24 25 import java.util.ArrayList; 26 27 public class BatteryController extends BroadcastReceiver { 28 private static final String TAG = "StatusBar.BatteryController"; 29 30 31 private ArrayList<BatteryStateChangeCallback> mChangeCallbacks = 32 new ArrayList<BatteryStateChangeCallback>(); 33 34 public interface BatteryStateChangeCallback { 35 public void onBatteryLevelChanged(int level, boolean pluggedIn); 36 } 37 38 public BatteryController(Context context) { 39 IntentFilter filter = new IntentFilter(); 40 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 41 context.registerReceiver(this, filter); 42 } 43 44 public void addStateChangedCallback(BatteryStateChangeCallback cb) { 45 mChangeCallbacks.add(cb); 46 } 47 48 public void onReceive(Context context, Intent intent) { 49 final String action = intent.getAction(); 50 if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { 51 final int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); 52 final int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 53 BatteryManager.BATTERY_STATUS_UNKNOWN); 54 55 boolean plugged = false; 56 switch (status) { 57 case BatteryManager.BATTERY_STATUS_CHARGING: 58 case BatteryManager.BATTERY_STATUS_FULL: 59 plugged = true; 60 break; 61 } 62 63 for (BatteryStateChangeCallback cb : mChangeCallbacks) { 64 cb.onBatteryLevelChanged(level, plugged); 65 } 66 } 67 } 68 } 69