BatteryService.java revision 3001a035439d8134a7d70d796376d1dfbff3cdcd
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.Context;
24import android.content.Intent;
25import android.content.pm.PackageManager;
26import android.os.BatteryManager;
27import android.os.Binder;
28import android.os.RemoteException;
29import android.os.SystemClock;
30import android.os.UEventObserver;
31import android.util.EventLog;
32import android.util.Log;
33
34import java.io.FileDescriptor;
35import java.io.PrintWriter;
36import java.lang.String;
37
38/**
39 * <p>BatteryService monitors the charging status, and charge level of the device
40 * battery.  When these values change this service broadcasts the new values
41 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are
42 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED
43 * BATTERY_CHANGED} action.</p>
44 * <p>The new values are stored in the Intent data and can be retrieved by
45 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the
46 * following keys:</p>
47 * <p>&quot;scale&quot; - int, the maximum value for the charge level</p>
48 * <p>&quot;level&quot; - int, charge level, from 0 through &quot;scale&quot; inclusive</p>
49 * <p>&quot;status&quot; - String, the current charging status.<br />
50 * <p>&quot;health&quot; - String, the current battery health.<br />
51 * <p>&quot;present&quot; - boolean, true if the battery is present<br />
52 * <p>&quot;icon-small&quot; - int, suggested small icon to use for this state</p>
53 * <p>&quot;plugged&quot; - int, 0 if the device is not plugged in; 1 if plugged
54 * into an AC power adapter; 2 if plugged in via USB.</p>
55 * <p>&quot;voltage&quot; - int, current battery voltage in millivolts</p>
56 * <p>&quot;temperature&quot; - int, current battery temperature in tenths of
57 * a degree Centigrade</p>
58 * <p>&quot;technology&quot; - String, the type of battery installed, e.g. "Li-ion"</p>
59 */
60class BatteryService extends Binder {
61    private static final String TAG = BatteryService.class.getSimpleName();
62
63    static final int LOG_BATTERY_LEVEL = 2722;
64    static final int LOG_BATTERY_STATUS = 2723;
65    static final int LOG_BATTERY_DISCHARGE_STATUS = 2730;
66
67    static final int BATTERY_SCALE = 100;    // battery capacity is a percentage
68
69    // This should probably be exposed in the API, though it's not critical
70    private static final int BATTERY_PLUGGED_NONE = 0;
71
72    private final Context mContext;
73    private final IBatteryStats mBatteryStats;
74
75    private boolean mAcOnline;
76    private boolean mUsbOnline;
77    private int mBatteryStatus;
78    private int mBatteryHealth;
79    private boolean mBatteryPresent;
80    private int mBatteryLevel;
81    private int mBatteryVoltage;
82    private int mBatteryTemperature;
83    private String mBatteryTechnology;
84
85    private int mLastBatteryStatus;
86    private int mLastBatteryHealth;
87    private boolean mLastBatteryPresent;
88    private int mLastBatteryLevel;
89    private int mLastBatteryVoltage;
90    private int mLastBatteryTemperature;
91
92    private int mPlugType;
93    private int mLastPlugType = -1; // Extra state so we can detect first run
94
95    private long mDischargeStartTime;
96    private int mDischargeStartLevel;
97
98    public BatteryService(Context context) {
99        mContext = context;
100        mBatteryStats = BatteryStatsService.getService();
101
102        mUEventObserver.startObserving("SUBSYSTEM=power_supply");
103
104        // set initial status
105        update();
106    }
107
108    final boolean isPowered() {
109        // assume we are powered if battery state is unknown so the "stay on while plugged in" option will work.
110        return (mAcOnline || mUsbOnline || mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN);
111    }
112
113    final boolean isPowered(int plugTypeSet) {
114        // assume we are powered if battery state is unknown so
115        // the "stay on while plugged in" option will work.
116        if (mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
117            return true;
118        }
119        if (plugTypeSet == 0) {
120            return false;
121        }
122        int plugTypeBit = 0;
123        if (mAcOnline) {
124            plugTypeBit |= BatteryManager.BATTERY_PLUGGED_AC;
125        }
126        if (mUsbOnline) {
127            plugTypeBit |= BatteryManager.BATTERY_PLUGGED_USB;
128        }
129        return (plugTypeSet & plugTypeBit) != 0;
130    }
131
132    final int getPlugType() {
133        return mPlugType;
134    }
135
136    private UEventObserver mUEventObserver = new UEventObserver() {
137        @Override
138        public void onUEvent(UEventObserver.UEvent event) {
139            update();
140        }
141    };
142
143    // returns battery level as a percentage
144    final int getBatteryLevel() {
145        return mBatteryLevel;
146    }
147
148    private native void native_update();
149
150    private synchronized final void update() {
151        native_update();
152        if (mAcOnline) {
153            mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
154        } else if (mUsbOnline) {
155            mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
156        } else {
157            mPlugType = BATTERY_PLUGGED_NONE;
158        }
159        if (mBatteryStatus != mLastBatteryStatus ||
160                mBatteryHealth != mLastBatteryHealth ||
161                mBatteryPresent != mLastBatteryPresent ||
162                mBatteryLevel != mLastBatteryLevel ||
163                mPlugType != mLastPlugType ||
164                mBatteryVoltage != mLastBatteryVoltage ||
165                mBatteryTemperature != mLastBatteryTemperature) {
166
167            if (mPlugType != mLastPlugType) {
168                if (mLastPlugType == BATTERY_PLUGGED_NONE) {
169                    // discharging -> charging
170
171                    // There's no value in this data unless we've discharged at least once and the
172                    // battery level has changed; so don't log until it does.
173                    if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) {
174                        long duration = SystemClock.elapsedRealtime() - mDischargeStartTime;
175                        EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, duration,
176                                mDischargeStartLevel, mBatteryLevel);
177                        // make sure we see a discharge event before logging again
178                        mDischargeStartTime = 0;
179                    }
180                } else if (mPlugType == BATTERY_PLUGGED_NONE) {
181                    // charging -> discharging or we just powered up
182                    mDischargeStartTime = SystemClock.elapsedRealtime();
183                    mDischargeStartLevel = mBatteryLevel;
184                }
185            }
186            if (mBatteryStatus != mLastBatteryStatus ||
187                    mBatteryHealth != mLastBatteryHealth ||
188                    mBatteryPresent != mLastBatteryPresent ||
189                    mPlugType != mLastPlugType) {
190                EventLog.writeEvent(LOG_BATTERY_STATUS,
191                        mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0,
192                        mPlugType, mBatteryTechnology);
193            }
194            if (mBatteryLevel != mLastBatteryLevel ||
195                    mBatteryVoltage != mLastBatteryVoltage ||
196                    mBatteryTemperature != mLastBatteryTemperature) {
197                EventLog.writeEvent(LOG_BATTERY_LEVEL,
198                        mBatteryLevel, mBatteryVoltage, mBatteryTemperature);
199            }
200
201            mLastBatteryStatus = mBatteryStatus;
202            mLastBatteryHealth = mBatteryHealth;
203            mLastBatteryPresent = mBatteryPresent;
204            mLastBatteryLevel = mBatteryLevel;
205            mLastPlugType = mPlugType;
206            mLastBatteryVoltage = mBatteryVoltage;
207            mLastBatteryTemperature = mBatteryTemperature;
208
209            sendIntent();
210        }
211    }
212
213    private final void sendIntent() {
214        //  Pack up the values and broadcast them to everyone
215        Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
216        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
217        try {
218            mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE);
219        } catch (RemoteException e) {
220            // Should never happen.
221        }
222
223        int icon = getIcon(mBatteryLevel);
224
225        intent.putExtra("status", mBatteryStatus);
226        intent.putExtra("health", mBatteryHealth);
227        intent.putExtra("present", mBatteryPresent);
228        intent.putExtra("level", mBatteryLevel);
229        intent.putExtra("scale", BATTERY_SCALE);
230        intent.putExtra("icon-small", icon);
231        intent.putExtra("plugged", mPlugType);
232        intent.putExtra("voltage", mBatteryVoltage);
233        intent.putExtra("temperature", mBatteryTemperature);
234        intent.putExtra("technology", mBatteryTechnology);
235
236        if (false) {
237            Log.d(TAG, "updateBattery level:" + mBatteryLevel +
238                    " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus +
239                    " health:" + mBatteryHealth +  " present:" + mBatteryPresent +
240                    " voltage: " + mBatteryVoltage +
241                    " temperature: " + mBatteryTemperature +
242                    " technology: " + mBatteryTechnology +
243                    " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline +
244                    " icon:" + icon );
245        }
246
247        ActivityManagerNative.broadcastStickyIntent(intent, null);
248    }
249
250    private final int getIcon(int level) {
251        if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
252            return com.android.internal.R.drawable.stat_sys_battery_charge;
253        } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING ||
254                mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING ||
255                mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
256            return com.android.internal.R.drawable.stat_sys_battery;
257        } else {
258            return com.android.internal.R.drawable.stat_sys_battery_unknown;
259        }
260    }
261
262    @Override
263    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
264        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
265                != PackageManager.PERMISSION_GRANTED) {
266
267            pw.println("Permission Denial: can't dump Battery service from from pid="
268                    + Binder.getCallingPid()
269                    + ", uid=" + Binder.getCallingUid());
270            return;
271        }
272
273        synchronized (this) {
274            pw.println("Current Battery Service state:");
275            pw.println("  AC powered: " + mAcOnline);
276            pw.println("  USB powered: " + mUsbOnline);
277            pw.println("  status: " + mBatteryStatus);
278            pw.println("  health: " + mBatteryHealth);
279            pw.println("  present: " + mBatteryPresent);
280            pw.println("  level: " + mBatteryLevel);
281            pw.println("  scale: " + BATTERY_SCALE);
282            pw.println("  voltage:" + mBatteryVoltage);
283            pw.println("  temperature: " + mBatteryTemperature);
284            pw.println("  technology: " + mBatteryTechnology);
285        }
286    }
287}
288