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