BatteryService.java revision 875ecaa511ce36c8044ccdf48ee2a3e69dd633fe
1/* 2 * Copyright (C) 2006 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.server; 18 19import com.android.internal.app.IBatteryStats; 20import com.android.server.am.BatteryStatsService; 21 22import android.app.ActivityManagerNative; 23import android.content.ContentResolver; 24import android.content.Context; 25import android.content.Intent; 26import android.content.pm.PackageManager; 27import android.os.BatteryManager; 28import android.os.Binder; 29import android.os.FileUtils; 30import android.os.IBinder; 31import android.os.DropBoxManager; 32import android.os.RemoteException; 33import android.os.ServiceManager; 34import android.os.SystemClock; 35import android.os.UEventObserver; 36import android.provider.Settings; 37import android.util.EventLog; 38import android.util.Slog; 39 40import java.io.File; 41import java.io.FileDescriptor; 42import java.io.FileInputStream; 43import java.io.FileOutputStream; 44import java.io.IOException; 45import java.io.PrintWriter; 46 47 48/** 49 * <p>BatteryService monitors the charging status, and charge level of the device 50 * battery. When these values change this service broadcasts the new values 51 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are 52 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED 53 * BATTERY_CHANGED} action.</p> 54 * <p>The new values are stored in the Intent data and can be retrieved by 55 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the 56 * following keys:</p> 57 * <p>"scale" - int, the maximum value for the charge level</p> 58 * <p>"level" - int, charge level, from 0 through "scale" inclusive</p> 59 * <p>"status" - String, the current charging status.<br /> 60 * <p>"health" - String, the current battery health.<br /> 61 * <p>"present" - boolean, true if the battery is present<br /> 62 * <p>"icon-small" - int, suggested small icon to use for this state</p> 63 * <p>"plugged" - int, 0 if the device is not plugged in; 1 if plugged 64 * into an AC power adapter; 2 if plugged in via USB.</p> 65 * <p>"voltage" - int, current battery voltage in millivolts</p> 66 * <p>"temperature" - int, current battery temperature in tenths of 67 * a degree Centigrade</p> 68 * <p>"technology" - String, the type of battery installed, e.g. "Li-ion"</p> 69 */ 70class BatteryService extends Binder { 71 private static final String TAG = BatteryService.class.getSimpleName(); 72 73 private static final boolean LOCAL_LOGV = false; 74 75 static final int BATTERY_SCALE = 100; // battery capacity is a percentage 76 77 // Used locally for determining when to make a last ditch effort to log 78 // discharge stats before the device dies. 79 private static final int CRITICAL_BATTERY_LEVEL = 4; 80 81 private static final int DUMP_MAX_LENGTH = 24 * 1024; 82 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "-u" }; 83 private static final String BATTERY_STATS_SERVICE_NAME = "batteryinfo"; 84 85 private static final String DUMPSYS_DATA_PATH = "/data/system/"; 86 87 // This should probably be exposed in the API, though it's not critical 88 private static final int BATTERY_PLUGGED_NONE = 0; 89 90 private final Context mContext; 91 private final IBatteryStats mBatteryStats; 92 93 private boolean mAcOnline; 94 private boolean mUsbOnline; 95 private int mBatteryStatus; 96 private int mBatteryHealth; 97 private boolean mBatteryPresent; 98 private int mBatteryLevel; 99 private int mBatteryVoltage; 100 private int mBatteryTemperature; 101 private String mBatteryTechnology; 102 private boolean mBatteryLevelCritical; 103 private boolean mInvalidCharger; 104 105 private int mLastBatteryStatus; 106 private int mLastBatteryHealth; 107 private boolean mLastBatteryPresent; 108 private int mLastBatteryLevel; 109 private int mLastBatteryVoltage; 110 private int mLastBatteryTemperature; 111 private boolean mLastBatteryLevelCritical; 112 private boolean mLastInvalidCharger; 113 114 private int mLowBatteryWarningLevel; 115 private int mLowBatteryCloseWarningLevel; 116 117 private int mPlugType; 118 private int mLastPlugType = -1; // Extra state so we can detect first run 119 120 private long mDischargeStartTime; 121 private int mDischargeStartLevel; 122 123 private boolean mSentLowBatteryBroadcast = false; 124 125 public BatteryService(Context context) { 126 mContext = context; 127 mBatteryStats = BatteryStatsService.getService(); 128 129 mLowBatteryWarningLevel = mContext.getResources().getInteger( 130 com.android.internal.R.integer.config_lowBatteryWarningLevel); 131 mLowBatteryCloseWarningLevel = mContext.getResources().getInteger( 132 com.android.internal.R.integer.config_lowBatteryCloseWarningLevel); 133 134 mPowerSupplyObserver.startObserving("SUBSYSTEM=power_supply"); 135 136 // watch for invalid charger messages if the invalid_charger switch exists 137 if (new File("/sys/devices/virtual/switch/invalid_charger/state").exists()) { 138 mInvalidChargerObserver.startObserving("DEVPATH=/devices/virtual/switch/invalid_charger"); 139 } 140 141 // set initial status 142 update(); 143 } 144 145 final boolean isPowered() { 146 // assume we are powered if battery state is unknown so the "stay on while plugged in" option will work. 147 return (mAcOnline || mUsbOnline || mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN); 148 } 149 150 final boolean isPowered(int plugTypeSet) { 151 // assume we are powered if battery state is unknown so 152 // the "stay on while plugged in" option will work. 153 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) { 154 return true; 155 } 156 if (plugTypeSet == 0) { 157 return false; 158 } 159 int plugTypeBit = 0; 160 if (mAcOnline) { 161 plugTypeBit |= BatteryManager.BATTERY_PLUGGED_AC; 162 } 163 if (mUsbOnline) { 164 plugTypeBit |= BatteryManager.BATTERY_PLUGGED_USB; 165 } 166 return (plugTypeSet & plugTypeBit) != 0; 167 } 168 169 final int getPlugType() { 170 return mPlugType; 171 } 172 173 private UEventObserver mPowerSupplyObserver = new UEventObserver() { 174 @Override 175 public void onUEvent(UEventObserver.UEvent event) { 176 update(); 177 } 178 }; 179 180 private UEventObserver mInvalidChargerObserver = new UEventObserver() { 181 @Override 182 public void onUEvent(UEventObserver.UEvent event) { 183 boolean invalidCharger = "1".equals(event.get("SWITCH_STATE")); 184 if (mInvalidCharger != invalidCharger) { 185 mInvalidCharger = invalidCharger; 186 update(); 187 } 188 } 189 }; 190 191 // returns battery level as a percentage 192 final int getBatteryLevel() { 193 return mBatteryLevel; 194 } 195 196 void systemReady() { 197 // check our power situation now that it is safe to display the shutdown dialog. 198 shutdownIfNoPower(); 199 shutdownIfOverTemp(); 200 } 201 202 private final void shutdownIfNoPower() { 203 // shut down gracefully if our battery is critically low and we are not powered. 204 // wait until the system has booted before attempting to display the shutdown dialog. 205 if (mBatteryLevel == 0 && !isPowered() && ActivityManagerNative.isSystemReady()) { 206 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN); 207 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false); 208 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 209 mContext.startActivity(intent); 210 } 211 } 212 213 private final void shutdownIfOverTemp() { 214 // shut down gracefully if temperature is too high (> 68.0C) 215 // wait until the system has booted before attempting to display the shutdown dialog. 216 if (mBatteryTemperature > 680 && ActivityManagerNative.isSystemReady()) { 217 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN); 218 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false); 219 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 220 mContext.startActivity(intent); 221 } 222 } 223 224 private native void native_update(); 225 226 private synchronized final void update() { 227 native_update(); 228 229 boolean logOutlier = false; 230 long dischargeDuration = 0; 231 232 mBatteryLevelCritical = mBatteryLevel <= CRITICAL_BATTERY_LEVEL; 233 if (mAcOnline) { 234 mPlugType = BatteryManager.BATTERY_PLUGGED_AC; 235 } else if (mUsbOnline) { 236 mPlugType = BatteryManager.BATTERY_PLUGGED_USB; 237 } else { 238 mPlugType = BATTERY_PLUGGED_NONE; 239 } 240 241 // Let the battery stats keep track of the current level. 242 try { 243 mBatteryStats.setBatteryState(mBatteryStatus, mBatteryHealth, 244 mPlugType, mBatteryLevel, mBatteryTemperature, 245 mBatteryVoltage); 246 } catch (RemoteException e) { 247 // Should never happen. 248 } 249 250 shutdownIfNoPower(); 251 shutdownIfOverTemp(); 252 253 if (mBatteryStatus != mLastBatteryStatus || 254 mBatteryHealth != mLastBatteryHealth || 255 mBatteryPresent != mLastBatteryPresent || 256 mBatteryLevel != mLastBatteryLevel || 257 mPlugType != mLastPlugType || 258 mBatteryVoltage != mLastBatteryVoltage || 259 mBatteryTemperature != mLastBatteryTemperature || 260 mInvalidCharger != mLastInvalidCharger) { 261 262 if (mPlugType != mLastPlugType) { 263 if (mLastPlugType == BATTERY_PLUGGED_NONE) { 264 // discharging -> charging 265 266 // There's no value in this data unless we've discharged at least once and the 267 // battery level has changed; so don't log until it does. 268 if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) { 269 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime; 270 logOutlier = true; 271 EventLog.writeEvent(EventLogTags.BATTERY_DISCHARGE, dischargeDuration, 272 mDischargeStartLevel, mBatteryLevel); 273 // make sure we see a discharge event before logging again 274 mDischargeStartTime = 0; 275 } 276 } else if (mPlugType == BATTERY_PLUGGED_NONE) { 277 // charging -> discharging or we just powered up 278 mDischargeStartTime = SystemClock.elapsedRealtime(); 279 mDischargeStartLevel = mBatteryLevel; 280 } 281 } 282 if (mBatteryStatus != mLastBatteryStatus || 283 mBatteryHealth != mLastBatteryHealth || 284 mBatteryPresent != mLastBatteryPresent || 285 mPlugType != mLastPlugType) { 286 EventLog.writeEvent(EventLogTags.BATTERY_STATUS, 287 mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0, 288 mPlugType, mBatteryTechnology); 289 } 290 if (mBatteryLevel != mLastBatteryLevel || 291 mBatteryVoltage != mLastBatteryVoltage || 292 mBatteryTemperature != mLastBatteryTemperature) { 293 EventLog.writeEvent(EventLogTags.BATTERY_LEVEL, 294 mBatteryLevel, mBatteryVoltage, mBatteryTemperature); 295 } 296 if (mBatteryLevelCritical && !mLastBatteryLevelCritical && 297 mPlugType == BATTERY_PLUGGED_NONE) { 298 // We want to make sure we log discharge cycle outliers 299 // if the battery is about to die. 300 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime; 301 logOutlier = true; 302 } 303 304 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE; 305 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE; 306 307 /* The ACTION_BATTERY_LOW broadcast is sent in these situations: 308 * - is just un-plugged (previously was plugged) and battery level is 309 * less than or equal to WARNING, or 310 * - is not plugged and battery level falls to WARNING boundary 311 * (becomes <= mLowBatteryWarningLevel). 312 */ 313 final boolean sendBatteryLow = !plugged 314 && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN 315 && mBatteryLevel <= mLowBatteryWarningLevel 316 && (oldPlugged || mLastBatteryLevel > mLowBatteryWarningLevel); 317 318 sendIntent(); 319 320 // Separate broadcast is sent for power connected / not connected 321 // since the standard intent will not wake any applications and some 322 // applications may want to have smart behavior based on this. 323 Intent statusIntent = new Intent(); 324 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 325 if (mPlugType != 0 && mLastPlugType == 0) { 326 statusIntent.setAction(Intent.ACTION_POWER_CONNECTED); 327 mContext.sendBroadcast(statusIntent); 328 } 329 else if (mPlugType == 0 && mLastPlugType != 0) { 330 statusIntent.setAction(Intent.ACTION_POWER_DISCONNECTED); 331 mContext.sendBroadcast(statusIntent); 332 } 333 334 if (sendBatteryLow) { 335 mSentLowBatteryBroadcast = true; 336 statusIntent.setAction(Intent.ACTION_BATTERY_LOW); 337 mContext.sendBroadcast(statusIntent); 338 } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= mLowBatteryCloseWarningLevel) { 339 mSentLowBatteryBroadcast = false; 340 statusIntent.setAction(Intent.ACTION_BATTERY_OKAY); 341 mContext.sendBroadcast(statusIntent); 342 } 343 344 // This needs to be done after sendIntent() so that we get the lastest battery stats. 345 if (logOutlier && dischargeDuration != 0) { 346 logOutlier(dischargeDuration); 347 } 348 349 mLastBatteryStatus = mBatteryStatus; 350 mLastBatteryHealth = mBatteryHealth; 351 mLastBatteryPresent = mBatteryPresent; 352 mLastBatteryLevel = mBatteryLevel; 353 mLastPlugType = mPlugType; 354 mLastBatteryVoltage = mBatteryVoltage; 355 mLastBatteryTemperature = mBatteryTemperature; 356 mLastBatteryLevelCritical = mBatteryLevelCritical; 357 mLastInvalidCharger = mInvalidCharger; 358 } 359 } 360 361 private final void sendIntent() { 362 // Pack up the values and broadcast them to everyone 363 Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED); 364 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 365 | Intent.FLAG_RECEIVER_REPLACE_PENDING); 366 367 int icon = getIcon(mBatteryLevel); 368 369 intent.putExtra(BatteryManager.EXTRA_STATUS, mBatteryStatus); 370 intent.putExtra(BatteryManager.EXTRA_HEALTH, mBatteryHealth); 371 intent.putExtra(BatteryManager.EXTRA_PRESENT, mBatteryPresent); 372 intent.putExtra(BatteryManager.EXTRA_LEVEL, mBatteryLevel); 373 intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE); 374 intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon); 375 intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType); 376 intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mBatteryVoltage); 377 intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mBatteryTemperature); 378 intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mBatteryTechnology); 379 intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger); 380 381 if (false) { 382 Slog.d(TAG, "updateBattery level:" + mBatteryLevel + 383 " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus + 384 " health:" + mBatteryHealth + " present:" + mBatteryPresent + 385 " voltage: " + mBatteryVoltage + 386 " temperature: " + mBatteryTemperature + 387 " technology: " + mBatteryTechnology + 388 " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline + 389 " icon:" + icon + " invalid charger:" + mInvalidCharger); 390 } 391 392 ActivityManagerNative.broadcastStickyIntent(intent, null); 393 } 394 395 private final void logBatteryStats() { 396 IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME); 397 if (batteryInfoService == null) return; 398 399 DropBoxManager db = (DropBoxManager) mContext.getSystemService(Context.DROPBOX_SERVICE); 400 if (db == null || !db.isTagEnabled("BATTERY_DISCHARGE_INFO")) return; 401 402 File dumpFile = null; 403 FileOutputStream dumpStream = null; 404 try { 405 // dump the service to a file 406 dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump"); 407 dumpStream = new FileOutputStream(dumpFile); 408 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS); 409 FileUtils.sync(dumpStream); 410 411 // add dump file to drop box 412 db.addFile("BATTERY_DISCHARGE_INFO", dumpFile, DropBoxManager.IS_TEXT); 413 } catch (RemoteException e) { 414 Slog.e(TAG, "failed to dump battery service", e); 415 } catch (IOException e) { 416 Slog.e(TAG, "failed to write dumpsys file", e); 417 } finally { 418 // make sure we clean up 419 if (dumpStream != null) { 420 try { 421 dumpStream.close(); 422 } catch (IOException e) { 423 Slog.e(TAG, "failed to close dumpsys output stream"); 424 } 425 } 426 if (dumpFile != null && !dumpFile.delete()) { 427 Slog.e(TAG, "failed to delete temporary dumpsys file: " 428 + dumpFile.getAbsolutePath()); 429 } 430 } 431 } 432 433 private final void logOutlier(long duration) { 434 ContentResolver cr = mContext.getContentResolver(); 435 String dischargeThresholdString = Settings.Secure.getString(cr, 436 Settings.Secure.BATTERY_DISCHARGE_THRESHOLD); 437 String durationThresholdString = Settings.Secure.getString(cr, 438 Settings.Secure.BATTERY_DISCHARGE_DURATION_THRESHOLD); 439 440 if (dischargeThresholdString != null && durationThresholdString != null) { 441 try { 442 long durationThreshold = Long.parseLong(durationThresholdString); 443 int dischargeThreshold = Integer.parseInt(dischargeThresholdString); 444 if (duration <= durationThreshold && 445 mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) { 446 // If the discharge cycle is bad enough we want to know about it. 447 logBatteryStats(); 448 } 449 if (LOCAL_LOGV) Slog.v(TAG, "duration threshold: " + durationThreshold + 450 " discharge threshold: " + dischargeThreshold); 451 if (LOCAL_LOGV) Slog.v(TAG, "duration: " + duration + " discharge: " + 452 (mDischargeStartLevel - mBatteryLevel)); 453 } catch (NumberFormatException e) { 454 Slog.e(TAG, "Invalid DischargeThresholds GService string: " + 455 durationThresholdString + " or " + dischargeThresholdString); 456 return; 457 } 458 } 459 } 460 461 private final int getIcon(int level) { 462 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) { 463 return com.android.internal.R.drawable.stat_sys_battery_charge; 464 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING || 465 mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING || 466 mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) { 467 return com.android.internal.R.drawable.stat_sys_battery; 468 } else { 469 return com.android.internal.R.drawable.stat_sys_battery_unknown; 470 } 471 } 472 473 @Override 474 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 475 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 476 != PackageManager.PERMISSION_GRANTED) { 477 478 pw.println("Permission Denial: can't dump Battery service from from pid=" 479 + Binder.getCallingPid() 480 + ", uid=" + Binder.getCallingUid()); 481 return; 482 } 483 484 synchronized (this) { 485 pw.println("Current Battery Service state:"); 486 pw.println(" AC powered: " + mAcOnline); 487 pw.println(" USB powered: " + mUsbOnline); 488 pw.println(" status: " + mBatteryStatus); 489 pw.println(" health: " + mBatteryHealth); 490 pw.println(" present: " + mBatteryPresent); 491 pw.println(" level: " + mBatteryLevel); 492 pw.println(" scale: " + BATTERY_SCALE); 493 pw.println(" voltage:" + mBatteryVoltage); 494 pw.println(" temperature: " + mBatteryTemperature); 495 pw.println(" technology: " + mBatteryTechnology); 496 } 497 } 498} 499