BatteryService.java revision 93dc9fe96192dbe6f974ca5d1c7c1102eb4b325a
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.Debug; 30import android.os.IBinder; 31import android.os.RemoteException; 32import android.os.ServiceManager; 33import android.os.SystemClock; 34import android.os.UEventObserver; 35import android.provider.Checkin; 36import android.provider.Settings; 37import android.util.EventLog; 38import android.util.Log; 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/** 50 * <p>BatteryService monitors the charging status, and charge level of the device 51 * battery. When these values change this service broadcasts the new values 52 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are 53 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED 54 * BATTERY_CHANGED} action.</p> 55 * <p>The new values are stored in the Intent data and can be retrieved by 56 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the 57 * following keys:</p> 58 * <p>"scale" - int, the maximum value for the charge level</p> 59 * <p>"level" - int, charge level, from 0 through "scale" inclusive</p> 60 * <p>"status" - String, the current charging status.<br /> 61 * <p>"health" - String, the current battery health.<br /> 62 * <p>"present" - boolean, true if the battery is present<br /> 63 * <p>"icon-small" - int, suggested small icon to use for this state</p> 64 * <p>"plugged" - int, 0 if the device is not plugged in; 1 if plugged 65 * into an AC power adapter; 2 if plugged in via USB.</p> 66 * <p>"voltage" - int, current battery voltage in millivolts</p> 67 * <p>"temperature" - int, current battery temperature in tenths of 68 * a degree Centigrade</p> 69 * <p>"technology" - String, the type of battery installed, e.g. "Li-ion"</p> 70 */ 71class BatteryService extends Binder { 72 private static final String TAG = BatteryService.class.getSimpleName(); 73 74 private static final boolean LOCAL_LOGV = false; 75 76 static final int LOG_BATTERY_LEVEL = 2722; 77 static final int LOG_BATTERY_STATUS = 2723; 78 static final int LOG_BATTERY_DISCHARGE_STATUS = 2730; 79 80 static final int BATTERY_SCALE = 100; // battery capacity is a percentage 81 82 // Used locally for determining when to make a last ditch effort to log 83 // discharge stats before the device dies. 84 private static final int CRITICAL_BATTERY_LEVEL = 4; 85 86 private static final int DUMP_MAX_LENGTH = 24 * 1024; 87 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "-u" }; 88 private static final String BATTERY_STATS_SERVICE_NAME = "batteryinfo"; 89 90 private static final String DUMPSYS_DATA_PATH = "/data/system/"; 91 92 // This should probably be exposed in the API, though it's not critical 93 private static final int BATTERY_PLUGGED_NONE = 0; 94 95 private static final int BATTERY_LEVEL_CLOSE_WARNING = 20; 96 private static final int BATTERY_LEVEL_WARNING = 15; 97 98 private final Context mContext; 99 private final IBatteryStats mBatteryStats; 100 101 private boolean mAcOnline; 102 private boolean mUsbOnline; 103 private int mBatteryStatus; 104 private int mBatteryHealth; 105 private boolean mBatteryPresent; 106 private int mBatteryLevel; 107 private int mBatteryVoltage; 108 private int mBatteryTemperature; 109 private String mBatteryTechnology; 110 private boolean mBatteryLevelCritical; 111 112 private int mLastBatteryStatus; 113 private int mLastBatteryHealth; 114 private boolean mLastBatteryPresent; 115 private int mLastBatteryLevel; 116 private int mLastBatteryVoltage; 117 private int mLastBatteryTemperature; 118 private boolean mLastBatteryLevelCritical; 119 120 private int mPlugType; 121 private int mLastPlugType = -1; // Extra state so we can detect first run 122 123 private long mDischargeStartTime; 124 private int mDischargeStartLevel; 125 126 private boolean mSentLowBatteryBroadcast = false; 127 128 public BatteryService(Context context) { 129 mContext = context; 130 mBatteryStats = BatteryStatsService.getService(); 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 private native void native_update(); 179 180 private synchronized final void update() { 181 native_update(); 182 183 boolean logOutlier = false; 184 long dischargeDuration = 0; 185 186 mBatteryLevelCritical = mBatteryLevel <= CRITICAL_BATTERY_LEVEL; 187 if (mAcOnline) { 188 mPlugType = BatteryManager.BATTERY_PLUGGED_AC; 189 } else if (mUsbOnline) { 190 mPlugType = BatteryManager.BATTERY_PLUGGED_USB; 191 } else { 192 mPlugType = BATTERY_PLUGGED_NONE; 193 } 194 if (mBatteryStatus != mLastBatteryStatus || 195 mBatteryHealth != mLastBatteryHealth || 196 mBatteryPresent != mLastBatteryPresent || 197 mBatteryLevel != mLastBatteryLevel || 198 mPlugType != mLastPlugType || 199 mBatteryVoltage != mLastBatteryVoltage || 200 mBatteryTemperature != mLastBatteryTemperature) { 201 202 if (mPlugType != mLastPlugType) { 203 if (mLastPlugType == BATTERY_PLUGGED_NONE) { 204 // discharging -> charging 205 206 // There's no value in this data unless we've discharged at least once and the 207 // battery level has changed; so don't log until it does. 208 if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) { 209 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime; 210 logOutlier = true; 211 EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, dischargeDuration, 212 mDischargeStartLevel, mBatteryLevel); 213 // make sure we see a discharge event before logging again 214 mDischargeStartTime = 0; 215 } 216 } else if (mPlugType == BATTERY_PLUGGED_NONE) { 217 // charging -> discharging or we just powered up 218 mDischargeStartTime = SystemClock.elapsedRealtime(); 219 mDischargeStartLevel = mBatteryLevel; 220 } 221 } 222 if (mBatteryStatus != mLastBatteryStatus || 223 mBatteryHealth != mLastBatteryHealth || 224 mBatteryPresent != mLastBatteryPresent || 225 mPlugType != mLastPlugType) { 226 EventLog.writeEvent(LOG_BATTERY_STATUS, 227 mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0, 228 mPlugType, mBatteryTechnology); 229 } 230 if (mBatteryLevel != mLastBatteryLevel || 231 mBatteryVoltage != mLastBatteryVoltage || 232 mBatteryTemperature != mLastBatteryTemperature) { 233 EventLog.writeEvent(LOG_BATTERY_LEVEL, 234 mBatteryLevel, mBatteryVoltage, mBatteryTemperature); 235 } 236 if (mBatteryLevel != mLastBatteryLevel && mPlugType == BATTERY_PLUGGED_NONE) { 237 // If the battery level has changed and we are on battery, update the current level. 238 // This is used for discharge cycle tracking so this shouldn't be updated while the 239 // battery is charging. 240 try { 241 mBatteryStats.recordCurrentLevel(mBatteryLevel); 242 } catch (RemoteException e) { 243 // Should never happen. 244 } 245 } 246 if (mBatteryLevelCritical && !mLastBatteryLevelCritical && 247 mPlugType == BATTERY_PLUGGED_NONE) { 248 // We want to make sure we log discharge cycle outliers 249 // if the battery is about to die. 250 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime; 251 logOutlier = true; 252 } 253 254 // Separate broadcast is sent for power connected / not connected 255 // since the standard intent will not wake any applications and some 256 // applications may want to have smart behavior based on this. 257 Intent statusIntent = new Intent(); 258 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 259 if (mPlugType != 0 && mLastPlugType == 0) { 260 statusIntent.setAction(Intent.ACTION_POWER_CONNECTED); 261 mContext.sendBroadcast(statusIntent); 262 } 263 else if (mPlugType == 0 && mLastPlugType != 0) { 264 statusIntent.setAction(Intent.ACTION_POWER_DISCONNECTED); 265 mContext.sendBroadcast(statusIntent); 266 } 267 268 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE; 269 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE; 270 271 /* The ACTION_BATTERY_LOW broadcast is sent in these situations: 272 * - is just un-plugged (previously was plugged) and battery level is under WARNING, or 273 * - is not plugged and battery level crosses the WARNING boundary (becomes < 15). 274 */ 275 final boolean sendBatteryLow = !plugged 276 && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN 277 && mBatteryLevel < BATTERY_LEVEL_WARNING 278 && (oldPlugged || mLastBatteryLevel >= BATTERY_LEVEL_WARNING); 279 280 mLastBatteryStatus = mBatteryStatus; 281 mLastBatteryHealth = mBatteryHealth; 282 mLastBatteryPresent = mBatteryPresent; 283 mLastBatteryLevel = mBatteryLevel; 284 mLastPlugType = mPlugType; 285 mLastBatteryVoltage = mBatteryVoltage; 286 mLastBatteryTemperature = mBatteryTemperature; 287 mLastBatteryLevelCritical = mBatteryLevelCritical; 288 289 sendIntent(); 290 if (sendBatteryLow) { 291 mSentLowBatteryBroadcast = true; 292 statusIntent.setAction(Intent.ACTION_BATTERY_LOW); 293 mContext.sendBroadcast(statusIntent); 294 } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= BATTERY_LEVEL_CLOSE_WARNING) { 295 mSentLowBatteryBroadcast = false; 296 statusIntent.setAction(Intent.ACTION_BATTERY_OKAY); 297 mContext.sendBroadcast(statusIntent); 298 } 299 300 // This needs to be done after sendIntent() so that we get the lastest battery stats. 301 if (logOutlier && dischargeDuration != 0) { 302 logOutlier(dischargeDuration); 303 } 304 } 305 } 306 307 private final void sendIntent() { 308 // Pack up the values and broadcast them to everyone 309 Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED); 310 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 311 try { 312 mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE, mBatteryLevel); 313 } catch (RemoteException e) { 314 // Should never happen. 315 } 316 317 int icon = getIcon(mBatteryLevel); 318 319 intent.putExtra("status", mBatteryStatus); 320 intent.putExtra("health", mBatteryHealth); 321 intent.putExtra("present", mBatteryPresent); 322 intent.putExtra("level", mBatteryLevel); 323 intent.putExtra("scale", BATTERY_SCALE); 324 intent.putExtra("icon-small", icon); 325 intent.putExtra("plugged", mPlugType); 326 intent.putExtra("voltage", mBatteryVoltage); 327 intent.putExtra("temperature", mBatteryTemperature); 328 intent.putExtra("technology", mBatteryTechnology); 329 330 if (false) { 331 Log.d(TAG, "updateBattery level:" + mBatteryLevel + 332 " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus + 333 " health:" + mBatteryHealth + " present:" + mBatteryPresent + 334 " voltage: " + mBatteryVoltage + 335 " temperature: " + mBatteryTemperature + 336 " technology: " + mBatteryTechnology + 337 " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline + 338 " icon:" + icon ); 339 } 340 341 ActivityManagerNative.broadcastStickyIntent(intent, null); 342 } 343 344 private final void logBatteryStats() { 345 346 IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME); 347 if (batteryInfoService != null) { 348 byte[] buffer = new byte[DUMP_MAX_LENGTH]; 349 File dumpFile = null; 350 FileOutputStream dumpStream = null; 351 try { 352 // dump the service to a file 353 dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump"); 354 dumpStream = new FileOutputStream(dumpFile); 355 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS); 356 dumpStream.getFD().sync(); 357 358 // read dumped file above into buffer truncated to DUMP_MAX_LENGTH 359 // and insert into events table. 360 int length = (int) Math.min(dumpFile.length(), DUMP_MAX_LENGTH); 361 FileInputStream fileInputStream = new FileInputStream(dumpFile); 362 int nread = fileInputStream.read(buffer, 0, length); 363 if (nread > 0) { 364 Checkin.logEvent(mContext.getContentResolver(), 365 Checkin.Events.Tag.BATTERY_DISCHARGE_INFO, 366 new String(buffer, 0, nread)); 367 if (LOCAL_LOGV) Log.v(TAG, "dumped " + nread + "b from " + 368 batteryInfoService + "to log"); 369 if (LOCAL_LOGV) Log.v(TAG, "actual dump:" + new String(buffer, 0, nread)); 370 } 371 } catch (RemoteException e) { 372 Log.e(TAG, "failed to dump service '" + BATTERY_STATS_SERVICE_NAME + 373 "':" + e); 374 } catch (IOException e) { 375 Log.e(TAG, "failed to write dumpsys file: " + e); 376 } finally { 377 // make sure we clean up 378 if (dumpStream != null) { 379 try { 380 dumpStream.close(); 381 } catch (IOException e) { 382 Log.e(TAG, "failed to close dumpsys output stream"); 383 } 384 } 385 if (dumpFile != null && !dumpFile.delete()) { 386 Log.e(TAG, "failed to delete temporary dumpsys file: " 387 + dumpFile.getAbsolutePath()); 388 } 389 } 390 } 391 } 392 393 private final void logOutlier(long duration) { 394 ContentResolver cr = mContext.getContentResolver(); 395 String dischargeThresholdString = Settings.Gservices.getString(cr, 396 Settings.Gservices.BATTERY_DISCHARGE_THRESHOLD); 397 String durationThresholdString = Settings.Gservices.getString(cr, 398 Settings.Gservices.BATTERY_DISCHARGE_DURATION_THRESHOLD); 399 400 if (dischargeThresholdString != null && durationThresholdString != null) { 401 try { 402 long durationThreshold = Long.parseLong(durationThresholdString); 403 int dischargeThreshold = Integer.parseInt(dischargeThresholdString); 404 if (duration <= durationThreshold && 405 mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) { 406 // If the discharge cycle is bad enough we want to know about it. 407 logBatteryStats(); 408 } 409 if (LOCAL_LOGV) Log.v(TAG, "duration threshold: " + durationThreshold + 410 " discharge threshold: " + dischargeThreshold); 411 if (LOCAL_LOGV) Log.v(TAG, "duration: " + duration + " discharge: " + 412 (mDischargeStartLevel - mBatteryLevel)); 413 } catch (NumberFormatException e) { 414 Log.e(TAG, "Invalid DischargeThresholds GService string: " + 415 durationThresholdString + " or " + dischargeThresholdString); 416 return; 417 } 418 } 419 } 420 421 private final int getIcon(int level) { 422 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) { 423 return com.android.internal.R.drawable.stat_sys_battery_charge; 424 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING || 425 mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING || 426 mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) { 427 return com.android.internal.R.drawable.stat_sys_battery; 428 } else { 429 return com.android.internal.R.drawable.stat_sys_battery_unknown; 430 } 431 } 432 433 @Override 434 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 435 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 436 != PackageManager.PERMISSION_GRANTED) { 437 438 pw.println("Permission Denial: can't dump Battery service from from pid=" 439 + Binder.getCallingPid() 440 + ", uid=" + Binder.getCallingUid()); 441 return; 442 } 443 444 synchronized (this) { 445 pw.println("Current Battery Service state:"); 446 pw.println(" AC powered: " + mAcOnline); 447 pw.println(" USB powered: " + mUsbOnline); 448 pw.println(" status: " + mBatteryStatus); 449 pw.println(" health: " + mBatteryHealth); 450 pw.println(" present: " + mBatteryPresent); 451 pw.println(" level: " + mBatteryLevel); 452 pw.println(" scale: " + BATTERY_SCALE); 453 pw.println(" voltage:" + mBatteryVoltage); 454 pw.println(" temperature: " + mBatteryTemperature); 455 pw.println(" technology: " + mBatteryTechnology); 456 } 457 } 458} 459