1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server;
import com.android.internal.app.IBatteryStats;
import com.android.server.am.BatteryStatsService;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.content.BroadcastReceiver;
import android.content.ContentQueryMap;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.BatteryStats;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.IPowerManager;
import android.os.LocalPowerManager;
import android.os.Power;
import android.os.PowerManager;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
import android.provider.Settings.SettingNotFoundException;
import android.provider.Settings;
import android.util.EventLog;
import android.util.Log;
import android.view.WindowManagerPolicy;
import static android.provider.Settings.System.DIM_SCREEN;
import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
class PowerManagerService extends IPowerManager.Stub
implements LocalPowerManager, Watchdog.Monitor, SensorEventListener {
private static final String TAG = "PowerManagerService";
static final String PARTIAL_NAME = "PowerManagerService";
private static final boolean LOG_PARTIAL_WL = false;
// Indicates whether touch-down cycles should be logged as part of the
// LOG_POWER_SCREEN_STATE log events
private static final boolean LOG_TOUCH_DOWNS = true;
private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
| PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.SCREEN_BRIGHT_WAKE_LOCK
| PowerManager.FULL_WAKE_LOCK
| PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
// time since last state: time since last event:
// The short keylight delay comes from Gservices; this is the default.
private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
// trigger proximity if distance is less than 5 cm
private static final float PROXIMITY_THRESHOLD = 5.0f;
// Cached Gservices settings; see updateGservicesValues()
private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
// flags for setPowerState
private static final int SCREEN_ON_BIT = 0x00000001;
private static final int SCREEN_BRIGHT_BIT = 0x00000002;
private static final int BUTTON_BRIGHT_BIT = 0x00000004;
private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
private static final int BATTERY_LOW_BIT = 0x00000010;
// values for setPowerState
// SCREEN_OFF == everything off
private static final int SCREEN_OFF = 0x00000000;
// SCREEN_DIM == screen on, screen backlight dim
private static final int SCREEN_DIM = SCREEN_ON_BIT;
// SCREEN_BRIGHT == screen on, screen backlight bright
private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
// SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
// SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
// used for noChangeLights in setPowerState()
private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
static final boolean ANIMATE_SCREEN_LIGHTS = true;
static final boolean ANIMATE_BUTTON_LIGHTS = false;
static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
static final int ANIM_STEPS = 60/4;
// These magic numbers are the initial state of the LEDs at boot. Ideally
// we should read them from the driver, but our current hardware returns 0
// for the initial value. Oops!
static final int INITIAL_SCREEN_BRIGHTNESS = 255;
static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
static final int LOG_POWER_SLEEP_REQUESTED = 2724;
static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
static final int LOG_POWER_SCREEN_STATE = 2728;
static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
private final int MY_UID;
private boolean mDoneBooting = false;
private int mStayOnConditions = 0;
private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
private int[] mBroadcastWhy = new int[3];
private int mPartialCount = 0;
private int mProximityCount = 0;
private int mPowerState;
private boolean mOffBecauseOfUser;
private int mUserState;
private boolean mKeyboardVisible = false;
private boolean mUserActivityAllowed = true;
private boolean mProximitySensorActive = false;
private int mTotalDelaySetting;
private int mKeylightDelay;
private int mDimDelay;
private int mScreenOffDelay;
private int mWakeLockState;
private long mLastEventTime = 0;
private long mScreenOffTime;
private volatile WindowManagerPolicy mPolicy;
private final LockList mLocks = new LockList();
private Intent mScreenOffIntent;
private Intent mScreenOnIntent;
private HardwareService mHardware;
private Context mContext;
private UnsynchronizedWakeLock mBroadcastWakeLock;
private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
private HandlerThread mHandlerThread;
private Handler mHandler;
private TimeoutTask mTimeoutTask = new TimeoutTask();
private LightAnimator mLightAnimator = new LightAnimator();
private final BrightnessState mScreenBrightness
= new BrightnessState(SCREEN_BRIGHT_BIT);
private final BrightnessState mKeyboardBrightness
= new BrightnessState(KEYBOARD_BRIGHT_BIT);
private final BrightnessState mButtonBrightness
= new BrightnessState(BUTTON_BRIGHT_BIT);
private boolean mStillNeedSleepNotification;
private boolean mIsPowered = false;
private IActivityManager mActivityService;
private IBatteryStats mBatteryStats;
private BatteryService mBatteryService;
private SensorManager mSensorManager;
private Sensor mProximitySensor;
private boolean mDimScreen = true;
private long mNextTimeout;
private volatile int mPokey = 0;
private volatile boolean mPokeAwakeOnSet = false;
private volatile boolean mInitComplete = false;
private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
private long mScreenOnTime;
private long mScreenOnStartTime;
private boolean mPreventScreenOn;
private int mScreenBrightnessOverride = -1;
// Used when logging number and duration of touch-down cycles
private long mTotalTouchDownTime;
private long mLastTouchDown;
private int mTouchCycles;
// could be either static or controllable at runtime
private static final boolean mSpew = false;
/*
static PrintStream mLog;
static {
try {
mLog = new PrintStream("/data/power.log");
}
catch (FileNotFoundException e) {
android.util.Log.e(TAG, "Life is hard", e);
}
}
static class Log {
static void d(String tag, String s) {
mLog.println(s);
android.util.Log.d(tag, s);
}
static void i(String tag, String s) {
mLog.println(s);
android.util.Log.i(tag, s);
}
static void w(String tag, String s) {
mLog.println(s);
android.util.Log.w(tag, s);
}
static void e(String tag, String s) {
mLog.println(s);
android.util.Log.e(tag, s);
}
}
*/
/**
* This class works around a deadlock between the lock in PowerManager.WakeLock
* and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
* mToken object so it can be accessed from any thread, but it calls into here
* with its lock held. This class is essentially a reimplementation of
* PowerManager.WakeLock, but without that extra synchronized block, because we'll
* only call it with our own locks held.
*/
private class UnsynchronizedWakeLock {
int mFlags;
String mTag;
IBinder mToken;
int mCount = 0;
boolean mRefCounted;
UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
mFlags = flags;
mTag = tag;
mToken = new Binder();
mRefCounted = refCounted;
}
public void acquire() {
if (!mRefCounted || mCount++ == 0) {
long ident = Binder.clearCallingIdentity();
try {
PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
MY_UID, mTag);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
}
public void release() {
if (!mRefCounted || --mCount == 0) {
PowerManagerService.this.releaseWakeLockLocked(mToken, false);
}
if (mCount < 0) {
throw new RuntimeException("WakeLock under-locked " + mTag);
}
}
public String toString() {
return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
+ " mCount=" + mCount + ")";
}
}
private final class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
synchronized (mLocks) {
boolean wasPowered = mIsPowered;
mIsPowered = mBatteryService.isPowered();
if (mIsPowered != wasPowered) {
// update mStayOnWhilePluggedIn wake lock
updateWakeLockLocked();
// treat plugging and unplugging the devices as a user activity.
// users find it disconcerting when they unplug the device
// and it shuts off right away.
// temporarily set mUserActivityAllowed to true so this will work
// even when the keyguard is on.
synchronized (mLocks) {
forceUserActivityLocked();
}
}
}
}
}
/**
* Set the setting that determines whether the device stays on when plugged in.
* The argument is a bit string, with each bit specifying a power source that,
* when the device is connected to that source, causes the device to stay on.
* See {@link android.os.BatteryManager} for the list of power sources that
* can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
* and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
* @param val an {@code int} containing the bits that specify which power sources
* should cause the device to stay on.
*/
public void setStayOnSetting(int val) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
}
private class SettingsObserver implements Observer {
private int getInt(String name) {
return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
}
public void update(Observable o, Object arg) {
synchronized (mLocks) {
// STAY_ON_WHILE_PLUGGED_IN
mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
updateWakeLockLocked();
// SCREEN_OFF_TIMEOUT
mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
// DIM_SCREEN
//mDimScreen = getInt(DIM_SCREEN) != 0;
// recalculate everything
setScreenOffTimeoutsLocked();
}
}
}
PowerManagerService()
{
// Hack to get our uid... should have a func for this.
long token = Binder.clearCallingIdentity();
MY_UID = Binder.getCallingUid();
Binder.restoreCallingIdentity(token);
// XXX remove this when the kernel doesn't timeout wake locks
Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
// assume nothing is on yet
mUserState = mPowerState = 0;
// Add ourself to the Watchdog monitors.
Watchdog.getInstance().addMonitor(this);
mScreenOnStartTime = SystemClock.elapsedRealtime();
}
private ContentQueryMap mSettings;
void init(Context context, HardwareService hardware, IActivityManager activity,
BatteryService battery) {
mHardware = hardware;
mContext = context;
mActivityService = activity;
mBatteryStats = BatteryStatsService.getService();
mBatteryService = battery;
mHandlerThread = new HandlerThread("PowerManagerService") {
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
initInThread();
}
};
mHandlerThread.start();
synchronized (mHandlerThread) {
while (!mInitComplete) {
try {
mHandlerThread.wait();
} catch (InterruptedException e) {
// Ignore
}
}
}
}
void initInThread() {
mHandler = new Handler();
mBroadcastWakeLock = new UnsynchronizedWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
ContentResolver resolver = mContext.getContentResolver();
Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
"(" + Settings.System.NAME + "=?) or ("
+ Settings.System.NAME + "=?) or ("
+ Settings.System.NAME + "=?)",
new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN},
null);
mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
SettingsObserver settingsObserver = new SettingsObserver();
mSettings.addObserver(settingsObserver);
// pretend that the settings changed so we will get their initial state
settingsObserver.update(mSettings, null);
// register for the battery changed notifications
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
mContext.registerReceiver(new BatteryReceiver(), filter);
// Listen for Gservices changes
IntentFilter gservicesChangedFilter =
new IntentFilter(Settings.Gservices.CHANGED_ACTION);
mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
// And explicitly do the initial update of our cached settings
updateGservicesValues();
// turn everything on
setPowerState(ALL_BRIGHT);
// set auto brightness mode to user setting
boolean brightnessMode = Settings.System.getInt(resolver, SCREEN_BRIGHTNESS_MODE, 1) != 0;
mHardware.setAutoBrightness_UNCHECKED(brightnessMode);
synchronized (mHandlerThread) {
mInitComplete = true;
mHandlerThread.notifyAll();
}
}
private class WakeLock implements IBinder.DeathRecipient
{
WakeLock(int f, IBinder b, String t, int u) {
super();
flags = f;
binder = b;
tag = t;
uid = u == MY_UID ? Process.SYSTEM_UID : u;
if (u != MY_UID || (
!"KEEP_SCREEN_ON_FLAG".equals(tag)
&& !"KeyInputQueue".equals(tag))) {
monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
? BatteryStats.WAKE_TYPE_PARTIAL
: BatteryStats.WAKE_TYPE_FULL;
} else {
monitorType = -1;
}
try {
b.linkToDeath(this, 0);
} catch (RemoteException e) {
binderDied();
}
}
public void binderDied() {
synchronized (mLocks) {
releaseWakeLockLocked(this.binder, true);
}
}
final int flags;
final IBinder binder;
final String tag;
final int uid;
final int monitorType;
boolean activated = true;
int minState;
}
private void updateWakeLockLocked() {
if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
// keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
mStayOnWhilePluggedInScreenDimLock.acquire();
mStayOnWhilePluggedInPartialLock.acquire();
} else {
mStayOnWhilePluggedInScreenDimLock.release();
mStayOnWhilePluggedInPartialLock.release();
}
}
private boolean isScreenLock(int flags)
{
int n = flags & LOCK_MASK;
return n == PowerManager.FULL_WAKE_LOCK
|| n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
|| n == PowerManager.SCREEN_DIM_WAKE_LOCK;
}
public void acquireWakeLock(int flags, IBinder lock, String tag) {
int uid = Binder.getCallingUid();
if (uid != Process.myUid()) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
}
long ident = Binder.clearCallingIdentity();
try {
synchronized (mLocks) {
acquireWakeLockLocked(flags, lock, uid, tag);
}
} finally {
Binder.restoreCallingIdentity(ident);
}
}
public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
int acquireUid = -1;
String acquireName = null;
int acquireType = -1;
if (mSpew) {
Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
}
int index = mLocks.getIndex(lock);
WakeLock wl;
boolean newlock;
if (index < 0) {
wl = new WakeLock(flags, lock, tag, uid);
switch (wl.flags & LOCK_MASK)
{
case PowerManager.FULL_WAKE_LOCK:
wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
break;
case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
wl.minState = SCREEN_BRIGHT;
break;
case PowerManager.SCREEN_DIM_WAKE_LOCK:
wl.minState = SCREEN_DIM;
break;
case PowerManager.PARTIAL_WAKE_LOCK:
case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
break;
default:
// just log and bail. we're in the server, so don't
// throw an exception.
Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
+ " flags=" + flags);
return;
}
mLocks.addLock(wl);
newlock = true;
} else {
wl = mLocks.get(index);
newlock = false;
}
if (isScreenLock(flags)) {
// if this causes a wakeup, we reactivate all of the locks and
// set it to whatever they want. otherwise, we modulate that
// by the current state so we never turn it more on than
// it already is.
if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
int oldWakeLockState = mWakeLockState;
mWakeLockState = mLocks.reactivateScreenLocksLocked();
if (mSpew) {
Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
+ " mWakeLockState=0x"
+ Integer.toHexString(mWakeLockState)
+ " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
}
} else {
if (mSpew) {
Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
+ " mLocks.gatherState()=0x"
+ Integer.toHexString(mLocks.gatherState())
+ " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
}
mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
}
setPowerState(mWakeLockState | mUserState);
}
else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
if (newlock) {
mPartialCount++;
if (mPartialCount == 1) {
if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
}
}
Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
} else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
mProximityCount++;
if (mProximityCount == 1) {
enableProximityLockLocked();
}
}
if (newlock) {
acquireUid = wl.uid;
acquireName = wl.tag;
acquireType = wl.monitorType;
}
if (acquireType >= 0) {
try {
mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
} catch (RemoteException e) {
// Ignore
}
}
}
public void releaseWakeLock(IBinder lock) {
int uid = Binder.getCallingUid();
if (uid != Process.myUid()) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
}
synchronized (mLocks) {
releaseWakeLockLocked(lock, false);
}
}
private void releaseWakeLockLocked(IBinder lock, boolean death) {
int releaseUid;
String releaseName;
int releaseType;
WakeLock wl = mLocks.removeLock(lock);
if (wl == null) {
return;
}
if (mSpew) {
Log.d(TAG, "releaseWakeLock flags=0x"
+ Integer.toHexString(wl.flags) + " tag=" + wl.tag);
}
if (isScreenLock(wl.flags)) {
mWakeLockState = mLocks.gatherState();
// goes in the middle to reduce flicker
if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
userActivity(SystemClock.uptimeMillis(), false);
}
setPowerState(mWakeLockState | mUserState);
}
else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
mPartialCount--;
if (mPartialCount == 0) {
if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
Power.releaseWakeLock(PARTIAL_NAME);
}
} else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
mProximityCount--;
if (mProximityCount == 0) {
disableProximityLockLocked();
}
}
// Unlink the lock from the binder.
wl.binder.unlinkToDeath(wl, 0);
releaseUid = wl.uid;
releaseName = wl.tag;
releaseType = wl.monitorType;
if (releaseType >= 0) {
long origId = Binder.clearCallingIdentity();
try {
mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
} catch (RemoteException e) {
// Ignore
} finally {
Binder.restoreCallingIdentity(origId);
}
}
}
private class PokeLock implements IBinder.DeathRecipient
{
PokeLock(int p, IBinder b, String t) {
super();
this.pokey = p;
this.binder = b;
this.tag = t;
try {
b.linkToDeath(this, 0);
} catch (RemoteException e) {
binderDied();
}
}
public void binderDied() {
setPokeLock(0, this.binder, this.tag);
}
int pokey;
IBinder binder;
String tag;
boolean awakeOnSet;
}
public void setPokeLock(int pokey, IBinder token, String tag) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
if (token == null) {
Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
return;
}
if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
+ " and POKE_LOCK_MEDIUM_TIMEOUT");
}
synchronized (mLocks) {
if (pokey != 0) {
PokeLock p = mPokeLocks.get(token);
int oldPokey = 0;
if (p != null) {
oldPokey = p.pokey;
p.pokey = pokey;
} else {
p = new PokeLock(pokey, token, tag);
mPokeLocks.put(token, p);
}
int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
p.awakeOnSet = true;
}
} else {
PokeLock rLock = mPokeLocks.remove(token);
if (rLock != null) {
token.unlinkToDeath(rLock, 0);
}
}
int oldPokey = mPokey;
int cumulative = 0;
boolean oldAwakeOnSet = mPokeAwakeOnSet;
boolean awakeOnSet = false;
for (PokeLock p: mPokeLocks.values()) {
cumulative |= p.pokey;
if (p.awakeOnSet) {
awakeOnSet = true;
}
}
mPokey = cumulative;
mPokeAwakeOnSet = awakeOnSet;
int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
if (oldCumulativeTimeout != newCumulativeTimeout) {
setScreenOffTimeoutsLocked();
// reset the countdown timer, but use the existing nextState so it doesn't
// change anything
setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
}
}
}
private static String lockType(int type)
{
switch (type)
{
case PowerManager.FULL_WAKE_LOCK:
return "FULL_WAKE_LOCK ";
case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
return "SCREEN_BRIGHT_WAKE_LOCK ";
case PowerManager.SCREEN_DIM_WAKE_LOCK:
return "SCREEN_DIM_WAKE_LOCK ";
case PowerManager.PARTIAL_WAKE_LOCK:
return "PARTIAL_WAKE_LOCK ";
case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
default:
return "??? ";
}
}
private static String dumpPowerState(int state) {
return (((state & KEYBOARD_BRIGHT_BIT) != 0)
? "KEYBOARD_BRIGHT_BIT " : "")
+ (((state & SCREEN_BRIGHT_BIT) != 0)
? "SCREEN_BRIGHT_BIT " : "")
+ (((state & SCREEN_ON_BIT) != 0)
? "SCREEN_ON_BIT " : "")
+ (((state & BATTERY_LOW_BIT) != 0)
? "BATTERY_LOW_BIT " : "");
}
@Override
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
!= PackageManager.PERMISSION_GRANTED) {
pw.println("Permission Denial: can't dump PowerManager from from pid="
+ Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid());
return;
}
long now = SystemClock.uptimeMillis();
pw.println("Power Manager State:");
pw.println(" mIsPowered=" + mIsPowered
+ " mPowerState=" + mPowerState
+ " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
+ " ms");
pw.println(" mPartialCount=" + mPartialCount);
pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
pw.println(" mUserState=" + dumpPowerState(mUserState));
pw.println(" mPowerState=" + dumpPowerState(mPowerState));
pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
+ " " + ((mNextTimeout-now)/1000) + "s from now");
pw.println(" mDimScreen=" + mDimScreen
+ " mStayOnConditions=" + mStayOnConditions);
pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
+ " mUserState=" + mUserState);
pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
+ ',' + mBroadcastQueue[2] + "}");
pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
+ ',' + mBroadcastWhy[2] + "}");
pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
pw.println(" mKeyboardVisible=" + mKeyboardVisible
+ " mUserActivityAllowed=" + mUserActivityAllowed);
pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
+ " mScreenOffDelay=" + mScreenOffDelay);
pw.println(" mPreventScreenOn=" + mPreventScreenOn
+ " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
mScreenBrightness.dump(pw, " mScreenBrightness: ");
mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
mButtonBrightness.dump(pw, " mButtonBrightness: ");
int N = mLocks.size();
pw.println();
pw.println("mLocks.size=" + N + ":");
for (int i=0; i<N; i++) {
WakeLock wl = mLocks.get(i);
String type = lockType(wl.flags & LOCK_MASK);
String acquireCausesWakeup = "";
if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
}
String activated = "";
if (wl.activated) {
activated = " activated";
}
pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
+ activated + " (minState=" + wl.minState + ")");
}
pw.println();
pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
for (PokeLock p: mPokeLocks.values()) {
pw.println(" poke lock '" + p.tag + "':"
+ ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
+ ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
+ ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
? " POKE_LOCK_SHORT_TIMEOUT" : "")
+ ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
}
pw.println();
}
private void setTimeoutLocked(long now, int nextState)
{
if (mDoneBooting) {
mHandler.removeCallbacks(mTimeoutTask);
mTimeoutTask.nextState = nextState;
long when = now;
switch (nextState)
{
case SCREEN_BRIGHT:
when += mKeylightDelay;
break;
case SCREEN_DIM:
if (mDimDelay >= 0) {
when += mDimDelay;
break;
} else {
Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
}
case SCREEN_OFF:
synchronized (mLocks) {
when += mScreenOffDelay;
}
break;
}
if (mSpew) {
Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
+ " when=" + when);
}
mHandler.postAtTime(mTimeoutTask, when);
mNextTimeout = when; // for debugging
}
}
private void cancelTimerLocked()
{
mHandler.removeCallbacks(mTimeoutTask);
mTimeoutTask.nextState = -1;
}
private class TimeoutTask implements Runnable
{
int nextState; // access should be synchronized on mLocks
public void run()
{
synchronized (mLocks) {
if (mSpew) {
Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
}
if (nextState == -1) {
return;
}
mUserState = this.nextState;
setPowerState(this.nextState | mWakeLockState);
long now = SystemClock.uptimeMillis();
switch (this.nextState)
{
case SCREEN_BRIGHT:
if (mDimDelay >= 0) {
setTimeoutLocked(now, SCREEN_DIM);
break;
}
case SCREEN_DIM:
setTimeoutLocked(now, SCREEN_OFF);
break;
}
}
}
}
private void sendNotificationLocked(boolean on, int why)
{
if (!on) {
mStillNeedSleepNotification = false;
}
// Add to the queue.
int index = 0;
while (mBroadcastQueue[index] != -1) {
index++;
}
mBroadcastQueue[index] = on ? 1 : 0;
mBroadcastWhy[index] = why;
// If we added it position 2, then there is a pair that can be stripped.
// If we added it position 1 and we're turning the screen off, we can strip
// the pair and do nothing, because the screen is already off, and therefore
// keyguard has already been enabled.
// However, if we added it at position 1 and we're turning it on, then position
// 0 was to turn it off, and we can't strip that, because keyguard needs to come
// on, so have to run the queue then.
if (index == 2) {
// Also, while we're collapsing them, if it's going to be an "off," and one
// is off because of user, then use that, regardless of whether it's the first
// or second one.
if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
}
mBroadcastQueue[0] = on ? 1 : 0;
mBroadcastQueue[1] = -1;
mBroadcastQueue[2] = -1;
index = 0;
}
if (index == 1 && !on) {
mBroadcastQueue[0] = -1;
mBroadcastQueue[1] = -1;
index = -1;
// The wake lock was being held, but we're not actually going to do any
// broadcasts, so release the wake lock.
EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
mBroadcastWakeLock.release();
}
// Now send the message.
if (index >= 0) {
// Acquire the broadcast wake lock before changing the power
// state. It will be release after the broadcast is sent.
// We always increment the ref count for each notification in the queue
// and always decrement when that notification is handled.
mBroadcastWakeLock.acquire();
EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
mHandler.post(mNotificationTask);
}
}
private Runnable mNotificationTask = new Runnable()
{
public void run()
{
while (true) {
int value;
int why;
WindowManagerPolicy policy;
synchronized (mLocks) {
value = mBroadcastQueue[0];
why = mBroadcastWhy[0];
for (int i=0; i<2; i++) {
mBroadcastQueue[i] = mBroadcastQueue[i+1];
mBroadcastWhy[i] = mBroadcastWhy[i+1];
}
policy = getPolicyLocked();
}
if (value == 1) {
mScreenOnStart = SystemClock.uptimeMillis();
policy.screenTurnedOn();
try {
ActivityManagerNative.getDefault().wakingUp();
} catch (RemoteException e) {
// ignore it
}
if (mSpew) {
Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
}
if (mContext != null && ActivityManagerNative.isSystemReady()) {
mContext.sendOrderedBroadcast(mScreenOnIntent, null,
mScreenOnBroadcastDone, mHandler, 0, null, null);
} else {
synchronized (mLocks) {
EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
mBroadcastWakeLock.mCount);
mBroadcastWakeLock.release();
}
}
}
else if (value == 0) {
mScreenOffStart = SystemClock.uptimeMillis();
policy.screenTurnedOff(why);
try {
ActivityManagerNative.getDefault().goingToSleep();
} catch (RemoteException e) {
// ignore it.
}
if (mContext != null && ActivityManagerNative.isSystemReady()) {
mContext.sendOrderedBroadcast(mScreenOffIntent, null,
mScreenOffBroadcastDone, mHandler, 0, null, null);
} else {
synchronized (mLocks) {
EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
mBroadcastWakeLock.mCount);
mBroadcastWakeLock.release();
}
}
}
else {
// If we're in this case, then this handler is running for a previous
// paired transaction. mBroadcastWakeLock will already have been released.
break;
}
}
}
};
long mScreenOnStart;
private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
synchronized (mLocks) {
EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
mBroadcastWakeLock.release();
}
}
};
long mScreenOffStart;
private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
synchronized (mLocks) {
EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
mBroadcastWakeLock.release();
}
}
};
void logPointerUpEvent() {
if (LOG_TOUCH_DOWNS) {
mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
mLastTouchDown = 0;
}
}
void logPointerDownEvent() {
if (LOG_TOUCH_DOWNS) {
// If we are not already timing a down/up sequence
if (mLastTouchDown == 0) {
mLastTouchDown = SystemClock.elapsedRealtime();
mTouchCycles++;
}
}
}
/**
* Prevents the screen from turning on even if it *should* turn on due
* to a subsequent full wake lock being acquired.
* <p>
* This is a temporary hack that allows an activity to "cover up" any
* display glitches that happen during the activity's startup
* sequence. (Specifically, this API was added to work around a
* cosmetic bug in the "incoming call" sequence, where the lock screen
* would flicker briefly before the incoming call UI became visible.)
* TODO: There ought to be a more elegant way of doing this,
* probably by having the PowerManager and ActivityManager
* work together to let apps specify that the screen on/off
* state should be synchronized with the Activity lifecycle.
* <p>
* Note that calling preventScreenOn(true) will NOT turn the screen
* off if it's currently on. (This API only affects *future*
* acquisitions of full wake locks.)
* But calling preventScreenOn(false) WILL turn the screen on if
* it's currently off because of a prior preventScreenOn(true) call.
* <p>
* Any call to preventScreenOn(true) MUST be followed promptly by a call
* to preventScreenOn(false). In fact, if the preventScreenOn(false)
* call doesn't occur within 5 seconds, we'll turn the screen back on
* ourselves (and log a warning about it); this prevents a buggy app
* from disabling the screen forever.)
* <p>
* TODO: this feature should really be controlled by a new type of poke
* lock (rather than an IPowerManager call).
*/
public void preventScreenOn(boolean prevent) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
synchronized (mLocks) {
if (prevent) {
// First of all, grab a partial wake lock to
// make sure the CPU stays on during the entire
// preventScreenOn(true) -> preventScreenOn(false) sequence.
mPreventScreenOnPartialLock.acquire();
// Post a forceReenableScreen() call (for 5 seconds in the
// future) to make sure the matching preventScreenOn(false) call
// has happened by then.
mHandler.removeCallbacks(mForceReenableScreenTask);
mHandler.postDelayed(mForceReenableScreenTask, 5000);
// Finally, set the flag that prevents the screen from turning on.
// (Below, in setPowerState(), we'll check mPreventScreenOn and
// we *won't* call Power.setScreenState(true) if it's set.)
mPreventScreenOn = true;
} else {
// (Re)enable the screen.
mPreventScreenOn = false;
// We're "undoing" a the prior preventScreenOn(true) call, so we
// no longer need the 5-second safeguard.
mHandler.removeCallbacks(mForceReenableScreenTask);
// Forcibly turn on the screen if it's supposed to be on. (This
// handles the case where the screen is currently off because of
// a prior preventScreenOn(true) call.)
if ((mPowerState & SCREEN_ON_BIT) != 0) {
if (mSpew) {
Log.d(TAG,
"preventScreenOn: turning on after a prior preventScreenOn(true)!");
}
int err = Power.setScreenState(true);
if (err != 0) {
Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
}
}
// Release the partial wake lock that we held during the
// preventScreenOn(true) -> preventScreenOn(false) sequence.
mPreventScreenOnPartialLock.release();
}
}
}
public void setScreenBrightnessOverride(int brightness) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
synchronized (mLocks) {
if (mScreenBrightnessOverride != brightness) {
mScreenBrightnessOverride = brightness;
updateLightsLocked(mPowerState, SCREEN_ON_BIT);
}
}
}
/**
* Sanity-check that gets called 5 seconds after any call to
* preventScreenOn(true). This ensures that the original call
* is followed promptly by a call to preventScreenOn(false).
*/
private void forceReenableScreen() {
// We shouldn't get here at all if mPreventScreenOn is false, since
// we should have already removed any existing
// mForceReenableScreenTask messages...
if (!mPreventScreenOn) {
Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
return;
}
// Uh oh. It's been 5 seconds since a call to
// preventScreenOn(true) and we haven't re-enabled the screen yet.
// This means the app that called preventScreenOn(true) is either
// slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
// or buggy (i.e. it forgot to call preventScreenOn(false), or
// crashed before doing so.)
// Log a warning, and forcibly turn the screen back on.
Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
+ "Forcing the screen back on...");
preventScreenOn(false);
}
private Runnable mForceReenableScreenTask = new Runnable() {
public void run() {
forceReenableScreen();
}
};
private void setPowerState(int state)
{
setPowerState(state, false, false);
}
private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
{
synchronized (mLocks) {
int err;
if (mSpew) {
Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
+ " newState=0x" + Integer.toHexString(newState)
+ " noChangeLights=" + noChangeLights);
}
if (noChangeLights) {
newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
}
if (mProximitySensorActive) {
// don't turn on the screen when the proximity sensor lock is held
newState = (newState & ~SCREEN_BRIGHT);
}
if (batteryIsLow()) {
newState |= BATTERY_LOW_BIT;
} else {
newState &= ~BATTERY_LOW_BIT;
}
if (newState == mPowerState) {
return;
}
if (!mDoneBooting) {
newState |= ALL_BRIGHT;
}
boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
if (mSpew) {
Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
+ " newState=" + newState + " noChangeLights=" + noChangeLights);
Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
+ " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
+ " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
+ " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Log.d(TAG, " oldScreenOn=" + oldScreenOn
+ " newScreenOn=" + newScreenOn);
Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
+ " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
}
if (mPowerState != newState) {
updateLightsLocked(newState, 0);
mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
}
if (oldScreenOn != newScreenOn) {
if (newScreenOn) {
// When the user presses the power button, we need to always send out the
// notification that it's going to sleep so the keyguard goes on. But
// we can't do that until the screen fades out, so we don't show the keyguard
// too early.
if (mStillNeedSleepNotification) {
sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
}
// Turn on the screen UNLESS there was a prior
// preventScreenOn(true) request. (Note that the lifetime
// of a single preventScreenOn() request is limited to 5
// seconds to prevent a buggy app from disabling the
// screen forever; see forceReenableScreen().)
boolean reallyTurnScreenOn = true;
if (mSpew) {
Log.d(TAG, "- turning screen on... mPreventScreenOn = "
+ mPreventScreenOn);
}
if (mPreventScreenOn) {
if (mSpew) {
Log.d(TAG, "- PREVENTING screen from really turning on!");
}
reallyTurnScreenOn = false;
}
if (reallyTurnScreenOn) {
err = Power.setScreenState(true);
long identity = Binder.clearCallingIdentity();
try {
mBatteryStats.noteScreenBrightness(
getPreferredBrightness());
mBatteryStats.noteScreenOn();
} catch (RemoteException e) {
Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
} finally {
Binder.restoreCallingIdentity(identity);
}
} else {
Power.setScreenState(false);
// But continue as if we really did turn the screen on...
err = 0;
}
mScreenOnStartTime = SystemClock.elapsedRealtime();
mLastTouchDown = 0;
mTotalTouchDownTime = 0;
mTouchCycles = 0;
EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
mTotalTouchDownTime, mTouchCycles);
if (err == 0) {
mPowerState |= SCREEN_ON_BIT;
sendNotificationLocked(true, -1);
}
} else {
mScreenOffTime = SystemClock.elapsedRealtime();
long identity = Binder.clearCallingIdentity();
try {
mBatteryStats.noteScreenOff();
} catch (RemoteException e) {
Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
} finally {
Binder.restoreCallingIdentity(identity);
}
mPowerState &= ~SCREEN_ON_BIT;
if (!mScreenBrightness.animating) {
err = screenOffFinishedAnimatingLocked(becauseOfUser);
} else {
mOffBecauseOfUser = becauseOfUser;
err = 0;
mLastTouchDown = 0;
}
}
}
}
}
private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
// I don't think we need to check the current state here because all of these
// Power.setScreenState and sendNotificationLocked can both handle being
// called multiple times in the same state. -joeo
EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
mTotalTouchDownTime, mTouchCycles);
mLastTouchDown = 0;
int err = Power.setScreenState(false);
if (mScreenOnStartTime != 0) {
mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
mScreenOnStartTime = 0;
}
if (err == 0) {
int why = becauseOfUser
? WindowManagerPolicy.OFF_BECAUSE_OF_USER
: WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
sendNotificationLocked(false, why);
}
return err;
}
private boolean batteryIsLow() {
return (!mIsPowered &&
mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
}
private void updateLightsLocked(int newState, int forceState) {
final int oldState = mPowerState;
final int realDifference = (newState ^ oldState);
final int difference = realDifference | forceState;
if (difference == 0) {
return;
}
int offMask = 0;
int dimMask = 0;
int onMask = 0;
int preferredBrightness = getPreferredBrightness();
boolean startAnimation = false;
if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
if (ANIMATE_KEYBOARD_LIGHTS) {
if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
preferredBrightness);
} else {
mKeyboardBrightness.setTargetLocked(preferredBrightness,
ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Power.BRIGHTNESS_OFF);
}
startAnimation = true;
} else {
if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
offMask |= KEYBOARD_BRIGHT_BIT;
} else {
onMask |= KEYBOARD_BRIGHT_BIT;
}
}
}
if ((difference & BUTTON_BRIGHT_BIT) != 0) {
if (ANIMATE_BUTTON_LIGHTS) {
if ((newState & BUTTON_BRIGHT_BIT) == 0) {
mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
preferredBrightness);
} else {
mButtonBrightness.setTargetLocked(preferredBrightness,
ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Power.BRIGHTNESS_OFF);
}
startAnimation = true;
} else {
if ((newState & BUTTON_BRIGHT_BIT) == 0) {
offMask |= BUTTON_BRIGHT_BIT;
} else {
onMask |= BUTTON_BRIGHT_BIT;
}
}
}
if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
if (ANIMATE_SCREEN_LIGHTS) {
int nominalCurrentValue = -1;
// If there was an actual difference in the light state, then
// figure out the "ideal" current value based on the previous
// state. Otherwise, this is a change due to the brightness
// override, so we want to animate from whatever the current
// value is.
if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
nominalCurrentValue = preferredBrightness;
break;
case SCREEN_ON_BIT:
nominalCurrentValue = Power.BRIGHTNESS_DIM;
break;
case 0:
nominalCurrentValue = Power.BRIGHTNESS_OFF;
break;
case SCREEN_BRIGHT_BIT:
default:
// not possible
nominalCurrentValue = (int)mScreenBrightness.curValue;
break;
}
}
int brightness = preferredBrightness;
int steps = ANIM_STEPS;
if ((newState & SCREEN_BRIGHT_BIT) == 0) {
// dim or turn off backlight, depending on if the screen is on
// the scale is because the brightness ramp isn't linear and this biases
// it so the later parts take longer.
final float scale = 1.5f;
float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
if (ratio > 1.0f) ratio = 1.0f;
if ((newState & SCREEN_ON_BIT) == 0) {
if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
// was bright
steps = ANIM_STEPS;
} else {
// was dim
steps = (int)(ANIM_STEPS*ratio*scale);
}
brightness = Power.BRIGHTNESS_OFF;
} else {
if ((oldState & SCREEN_ON_BIT) != 0) {
// was bright
steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
} else {
// was dim
steps = (int)(ANIM_STEPS*ratio);
}
if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
// If the "stay on while plugged in" option is
// turned on, then the screen will often not
// automatically turn off while plugged in. To
// still have a sense of when it is inactive, we
// will then count going dim as turning off.
mScreenOffTime = SystemClock.elapsedRealtime();
}
brightness = Power.BRIGHTNESS_DIM;
}
}
long identity = Binder.clearCallingIdentity();
try {
mBatteryStats.noteScreenBrightness(brightness);
} catch (RemoteException e) {
// Nothing interesting to do.
} finally {
Binder.restoreCallingIdentity(identity);
}
if (mScreenBrightness.setTargetLocked(brightness,
steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
startAnimation = true;
}
} else {
if ((newState & SCREEN_BRIGHT_BIT) == 0) {
// dim or turn off backlight, depending on if the screen is on
if ((newState & SCREEN_ON_BIT) == 0) {
offMask |= SCREEN_BRIGHT_BIT;
} else {
dimMask |= SCREEN_BRIGHT_BIT;
}
} else {
onMask |= SCREEN_BRIGHT_BIT;
}
}
}
if (startAnimation) {
if (mSpew) {
Log.i(TAG, "Scheduling light animator!");
}
mHandler.removeCallbacks(mLightAnimator);
mHandler.post(mLightAnimator);
}
if (offMask != 0) {
//Log.i(TAG, "Setting brightess off: " + offMask);
setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
}
if (dimMask != 0) {
int brightness = Power.BRIGHTNESS_DIM;
if ((newState & BATTERY_LOW_BIT) != 0 &&
brightness > Power.BRIGHTNESS_LOW_BATTERY) {
brightness = Power.BRIGHTNESS_LOW_BATTERY;
}
//Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
setLightBrightness(dimMask, brightness);
}
if (onMask != 0) {
int brightness = getPreferredBrightness();
if ((newState & BATTERY_LOW_BIT) != 0 &&
brightness > Power.BRIGHTNESS_LOW_BATTERY) {
brightness = Power.BRIGHTNESS_LOW_BATTERY;
}
//Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
setLightBrightness(onMask, brightness);
}
}
private void setLightBrightness(int mask, int value) {
if ((mask & SCREEN_BRIGHT_BIT) != 0) {
mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
}
if ((mask & BUTTON_BRIGHT_BIT) != 0) {
mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
}
if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
}
}
class BrightnessState {
final int mask;
boolean initialized;
int targetValue;
float curValue;
float delta;
boolean animating;
BrightnessState(int m) {
mask = m;
}
public void dump(PrintWriter pw, String prefix) {
pw.println(prefix + "animating=" + animating
+ " targetValue=" + targetValue
+ " curValue=" + curValue
+ " delta=" + delta);
}
boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
int nominalCurrentValue) {
if (!initialized) {
initialized = true;
curValue = (float)initialValue;
} else if (targetValue == target) {
return false;
}
targetValue = target;
delta = (targetValue -
(nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
/ stepsToTarget;
if (mSpew) {
String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
+ " target=" + targetValue + " delta=" + delta
+ " nominalCurrentValue=" + nominalCurrentValue
+ noticeMe);
}
animating = true;
return true;
}
boolean stepLocked() {
if (!animating) return false;
if (false && mSpew) {
Log.i(TAG, "Step target " + mask + ": cur=" + curValue
+ " target=" + targetValue + " delta=" + delta);
}
curValue += delta;
int curIntValue = (int)curValue;
boolean more = true;
if (delta == 0) {
curValue = curIntValue = targetValue;
more = false;
} else if (delta > 0) {
if (curIntValue >= targetValue) {
curValue = curIntValue = targetValue;
more = false;
}
} else {
if (curIntValue <= targetValue) {
curValue = curIntValue = targetValue;
more = false;
}
}
//Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
setLightBrightness(mask, curIntValue);
animating = more;
if (!more) {
if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
}
}
return more;
}
}
private class LightAnimator implements Runnable {
public void run() {
synchronized (mLocks) {
long now = SystemClock.uptimeMillis();
boolean more = mScreenBrightness.stepLocked();
if (mKeyboardBrightness.stepLocked()) {
more = true;
}
if (mButtonBrightness.stepLocked()) {
more = true;
}
if (more) {
mHandler.postAtTime(mLightAnimator, now+(1000/60));
}
}
}
}
private int getPreferredBrightness() {
try {
if (mScreenBrightnessOverride >= 0) {
return mScreenBrightnessOverride;
}
final int brightness = Settings.System.getInt(mContext.getContentResolver(),
SCREEN_BRIGHTNESS);
// Don't let applications turn the screen all the way off
return Math.max(brightness, Power.BRIGHTNESS_DIM);
} catch (SettingNotFoundException snfe) {
return Power.BRIGHTNESS_ON;
}
}
boolean screenIsOn() {
synchronized (mLocks) {
return (mPowerState & SCREEN_ON_BIT) != 0;
}
}
boolean screenIsBright() {
synchronized (mLocks) {
return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
}
}
private void forceUserActivityLocked() {
boolean savedActivityAllowed = mUserActivityAllowed;
mUserActivityAllowed = true;
userActivity(SystemClock.uptimeMillis(), false);
mUserActivityAllowed = savedActivityAllowed;
}
public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
userActivity(time, noChangeLights, OTHER_EVENT, force);
}
public void userActivity(long time, boolean noChangeLights) {
userActivity(time, noChangeLights, OTHER_EVENT, false);
}
public void userActivity(long time, boolean noChangeLights, int eventType) {
userActivity(time, noChangeLights, eventType, false);
}
public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
//mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
&& (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
if (false) {
Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
}
return;
}
if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
&& (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
|| eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
if (false) {
Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
}
return;
}
if (false) {
if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Log.d(TAG, "userActivity !!!");//, new RuntimeException());
} else {
Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
}
}
synchronized (mLocks) {
if (mSpew) {
Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
+ " mUserActivityAllowed=" + mUserActivityAllowed
+ " mUserState=0x" + Integer.toHexString(mUserState)
+ " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
+ " mProximitySensorActive=" + mProximitySensorActive
+ " force=" + force);
}
if (mLastEventTime <= time || force) {
mLastEventTime = time;
if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
// Only turn on button backlights if a button was pressed.
if (eventType == BUTTON_EVENT) {
mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
} else {
// don't clear button/keyboard backlights when the screen is touched.
mUserState |= SCREEN_BRIGHT;
}
int uid = Binder.getCallingUid();
long ident = Binder.clearCallingIdentity();
try {
mBatteryStats.noteUserActivity(uid, eventType);
} catch (RemoteException e) {
// Ignore
} finally {
Binder.restoreCallingIdentity(ident);
}
mWakeLockState = mLocks.reactivateScreenLocksLocked();
setPowerState(mUserState | mWakeLockState, noChangeLights, true);
setTimeoutLocked(time, SCREEN_BRIGHT);
}
}
}
}
/**
* The user requested that we go to sleep (probably with the power button).
* This overrides all wake locks that are held.
*/
public void goToSleep(long time)
{
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
synchronized (mLocks) {
goToSleepLocked(time);
}
}
/**
* Returns the time the screen has been on since boot, in millis.
* @return screen on time
*/
public long getScreenOnTime() {
synchronized (mLocks) {
if (mScreenOnStartTime == 0) {
return mScreenOnTime;
} else {
return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
}
}
}
private void goToSleepLocked(long time) {
if (mLastEventTime <= time) {
mLastEventTime = time;
// cancel all of the wake locks
mWakeLockState = SCREEN_OFF;
int N = mLocks.size();
int numCleared = 0;
for (int i=0; i<N; i++) {
WakeLock wl = mLocks.get(i);
if (isScreenLock(wl.flags)) {
mLocks.get(i).activated = false;
numCleared++;
}
}
EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
mStillNeedSleepNotification = true;
mUserState = SCREEN_OFF;
setPowerState(SCREEN_OFF, false, true);
cancelTimerLocked();
}
}
public long timeSinceScreenOn() {
synchronized (mLocks) {
if ((mPowerState & SCREEN_ON_BIT) != 0) {
return 0;
}
return SystemClock.elapsedRealtime() - mScreenOffTime;
}
}
public void setKeyboardVisibility(boolean visible) {
synchronized (mLocks) {
if (mSpew) {
Log.d(TAG, "setKeyboardVisibility: " + visible);
}
mKeyboardVisible = visible;
// don't signal user activity if the screen is off; other code
// will take care of turning on due to a true change to the lid
// switch and synchronized with the lock screen.
if ((mPowerState & SCREEN_ON_BIT) != 0) {
userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
}
}
}
/**
* When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
*/
public void enableUserActivity(boolean enabled) {
synchronized (mLocks) {
mUserActivityAllowed = enabled;
mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
}
}
/** Sets the screen off timeouts:
* mKeylightDelay
* mDimDelay
* mScreenOffDelay
* */
private void setScreenOffTimeoutsLocked() {
if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
mDimDelay = -1;
mScreenOffDelay = 0;
} else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
mDimDelay = -1;
mScreenOffDelay = 0;
} else {
int totalDelay = mTotalDelaySetting;
mKeylightDelay = LONG_KEYLIGHT_DELAY;
if (totalDelay < 0) {
mScreenOffDelay = Integer.MAX_VALUE;
} else if (mKeylightDelay < totalDelay) {
// subtract the time that the keylight delay. This will give us the
// remainder of the time that we need to sleep to get the accurate
// screen off timeout.
mScreenOffDelay = totalDelay - mKeylightDelay;
} else {
mScreenOffDelay = 0;
}
if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
mScreenOffDelay = LONG_DIM_TIME;
} else {
mDimDelay = -1;
}
}
if (mSpew) {
Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
+ " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
+ " mDimScreen=" + mDimScreen);
}
}
/**
* Refreshes cached Gservices settings. Called once on startup, and
* on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
* GservicesChangedReceiver).
*/
private void updateGservicesValues() {
mShortKeylightDelay = Settings.Gservices.getInt(
mContext.getContentResolver(),
Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
SHORT_KEYLIGHT_DELAY_DEFAULT);
// Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
}
/**
* Receiver for the Gservices.CHANGED_ACTION broadcast intent,
* which tells us we need to refresh our cached Gservices settings.
*/
private class GservicesChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
updateGservicesValues();
}
}
private class LockList extends ArrayList<WakeLock>
{
void addLock(WakeLock wl)
{
int index = getIndex(wl.binder);
if (index < 0) {
this.add(wl);
}
}
WakeLock removeLock(IBinder binder)
{
int index = getIndex(binder);
if (index >= 0) {
return this.remove(index);
} else {
return null;
}
}
int getIndex(IBinder binder)
{
int N = this.size();
for (int i=0; i<N; i++) {
if (this.get(i).binder == binder) {
return i;
}
}
return -1;
}
int gatherState()
{
int result = 0;
int N = this.size();
for (int i=0; i<N; i++) {
WakeLock wl = this.get(i);
if (wl.activated) {
if (isScreenLock(wl.flags)) {
result |= wl.minState;
}
}
}
return result;
}
int reactivateScreenLocksLocked()
{
int result = 0;
int N = this.size();
for (int i=0; i<N; i++) {
WakeLock wl = this.get(i);
if (isScreenLock(wl.flags)) {
wl.activated = true;
result |= wl.minState;
}
}
return result;
}
}
void setPolicy(WindowManagerPolicy p) {
synchronized (mLocks) {
mPolicy = p;
mLocks.notifyAll();
}
}
WindowManagerPolicy getPolicyLocked() {
while (mPolicy == null || !mDoneBooting) {
try {
mLocks.wait();
} catch (InterruptedException e) {
// Ignore
}
}
return mPolicy;
}
void systemReady() {
synchronized (mLocks) {
Log.d(TAG, "system ready!");
mDoneBooting = true;
long identity = Binder.clearCallingIdentity();
try {
mBatteryStats.noteScreenBrightness(getPreferredBrightness());
mBatteryStats.noteScreenOn();
} catch (RemoteException e) {
// Nothing interesting to do.
} finally {
Binder.restoreCallingIdentity(identity);
}
userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
updateWakeLockLocked();
mLocks.notifyAll();
}
}
public void monitor() {
synchronized (mLocks) { }
}
public int getSupportedWakeLockFlags() {
int result = PowerManager.PARTIAL_WAKE_LOCK
| PowerManager.FULL_WAKE_LOCK
| PowerManager.SCREEN_DIM_WAKE_LOCK;
// call getSensorManager() to make sure mProximitySensor is initialized
getSensorManager();
if (mProximitySensor != null) {
result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
}
return result;
}
public void setBacklightBrightness(int brightness) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
// Don't let applications turn the screen all the way off
brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, brightness);
mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
long identity = Binder.clearCallingIdentity();
try {
mBatteryStats.noteScreenBrightness(brightness);
} catch (RemoteException e) {
Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
} finally {
Binder.restoreCallingIdentity(identity);
}
// update our animation state
if (ANIMATE_SCREEN_LIGHTS) {
mScreenBrightness.curValue = brightness;
mScreenBrightness.animating = false;
}
if (ANIMATE_KEYBOARD_LIGHTS) {
mKeyboardBrightness.curValue = brightness;
mKeyboardBrightness.animating = false;
}
if (ANIMATE_BUTTON_LIGHTS) {
mButtonBrightness.curValue = brightness;
mButtonBrightness.animating = false;
}
}
public void setAutoBrightness(boolean on) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
mHardware.setAutoBrightness_UNCHECKED(on);
}
private SensorManager getSensorManager() {
if (mSensorManager == null) {
mSensorManager = new SensorManager(mHandlerThread.getLooper());
mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
}
return mSensorManager;
}
private void enableProximityLockLocked() {
if (mSpew) {
Log.d(TAG, "enableProximityLockLocked");
}
mSensorManager.registerListener(this, mProximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
private void disableProximityLockLocked() {
if (mSpew) {
Log.d(TAG, "disableProximityLockLocked");
}
mSensorManager.unregisterListener(this);
synchronized (mLocks) {
if (mProximitySensorActive) {
mProximitySensorActive = false;
forceUserActivityLocked();
}
}
}
public void onSensorChanged(SensorEvent event) {
long milliseconds = event.timestamp / 1000000;
synchronized (mLocks) {
float distance = event.values[0];
// compare against getMaximumRange to support sensors that only return 0 or 1
if (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
distance < mProximitySensor.getMaximumRange()) {
if (mSpew) {
Log.d(TAG, "onSensorChanged: proximity active, distance: " + distance);
}
goToSleepLocked(milliseconds);
mProximitySensorActive = true;
} else {
// proximity sensor negative events trigger as user activity.
// temporarily set mUserActivityAllowed to true so this will work
// even when the keyguard is on.
if (mSpew) {
Log.d(TAG, "onSensorChanged: proximity inactive, distance: " + distance);
}
mProximitySensorActive = false;
forceUserActivityLocked();
}
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// ignore
}
}
|