summaryrefslogtreecommitdiffstats
path: root/src/com/android/music/MediaPlaybackService.java
blob: 17f2e6864d02844a4974b10831f262bfbe5de6ae (plain)
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
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
/*
 * 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.music;

import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.WallpaperManager;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.RemoteControlClient;
import android.media.RemoteControlClient.MetadataEditor;
import android.media.audiofx.AudioEffect;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.RemoteException;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * Provides "background" audio playback capabilities, allowing the user to
 * switch between activities without stopping playback.
 */
public class MediaPlaybackService extends Service implements
		SensorEventListener, Shaker.Callback {
	/**
	 * used to specify whether enqueue() should start playing the new list of
	 * files right away, next or once all the currently queued files have been
	 * played
	 */
	public static final int NOW = 1;
	public static final int NEXT = 2;
	public static final int LAST = 3;
	public static final int PLAYBACKSERVICE_STATUS = 1;

	public static final String PLAYSTATE_CHANGED = "com.android.music.playstatechanged";
	public static final String META_CHANGED = "com.android.music.metachanged";
	public static final String QUEUE_CHANGED = "com.android.music.queuechanged";
	public static final String REPEATMODE_CHANGED = "com.android.music.repeatmodechanged";
	public static final String SHUFFLEMODE_CHANGED = "com.android.music.shufflemodechanged";
	public static final String PROGRESSBAR_CHANGED = "com.android.music.progressbarchnaged";
	public static final String REFRESH_PROGRESSBAR = "com.android.music.refreshui";

	public static final int SHUFFLE_NONE = 0;
	public static final int SHUFFLE_NORMAL = 1;
	public static final int SHUFFLE_AUTO = 2;

	public static final int REPEAT_NONE = 0;
	public static final int REPEAT_CURRENT = 1;
	public static final int REPEAT_ALL = 2;

	public static final String SERVICECMD = "com.android.music.musicservicecommand";
	public static final String CMDNAME = "command";
	public static final String CMDTOGGLEPAUSE = "togglepause";
	public static final String CMDTOGGLEPAUSEDUMMY = "togglepausedummy";
	public static final String CMDSTOP = "stop";
	public static final String CMDPAUSE = "pause";
	public static final String CMDPREVIOUS = "previous";
	public static final String CMDNEXT = "next";
	public static final String CMDCYCLEREPEAT = "cyclerepeat";
	public static final String CMDTOGGLESHUFFLE = "toggleshuffle";
	public static final String CMDPLAY = "play";
	public static final String CMDNOTIF = "buttonId";

	public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause";
	public static final String TOGGLEPAUSE_ACTIONDUMMY = "com.android.music.musicservicecommand.togglepausedummy";
	public static final String PAUSE_ACTION = "com.android.music.musicservicecommand.pause";
	public static final String PREVIOUS_ACTION = "com.android.music.musicservicecommand.previous";
	public static final String NEXT_ACTION = "com.android.music.musicservicecommand.next";
	public static final String CYCLEREPEAT_ACTION = "com.android.music.musicservicecommand.cyclerepeat";
	public static final String TOGGLESHUFFLE_ACTION = "com.android.music.musicservicecommand.toggleshuffle";
	private static final String PLAYSTATUS_REQUEST = "com.android.music.playstatusrequest";
	private static final String PLAYSTATUS_RESPONSE = "com.android.music.playstatusresponse";

	private static final int TRACK_ENDED = 1;
	private static final int RELEASE_WAKELOCK = 2;
	private static final int SERVER_DIED = 3;
	private static final int FOCUSCHANGE = 4;
	private static final int FADEDOWN = 5;
	private static final int FADEUP = 6;
	private static final int MAX_HISTORY_SIZE = 100;

	private Notification status;
	private MultiPlayer mPlayer;
	private String mFileToPlay;
	private int mShuffleMode = SHUFFLE_NONE;
	private int mRepeatMode = REPEAT_NONE;
	private int mMediaMountedCount = 0;
	private long[] mAutoShuffleList = null;
	private long[] mPlayList = null;
	private int mPlayListLen = 0;
	private Vector<Integer> mHistory = new Vector<Integer>(MAX_HISTORY_SIZE);
	private Cursor mCursor;
	private int mPlayPos = -1;
	private static final String LOGTAG = "MediaPlaybackService";
	private final Shuffler mRand = new Shuffler();
	private int mOpenFailedCounter = 0;
	String[] mCursorCols = new String[] {
			"audio._id AS _id", // index must match IDCOLIDX below
			MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
			MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
			MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
			MediaStore.Audio.Media.ARTIST_ID,
			MediaStore.Audio.Media.IS_PODCAST, // index must match PODCASTCOLIDX
												// below
			MediaStore.Audio.Media.BOOKMARK // index must match BOOKMARKCOLIDX
											// below
	};
	private final static int IDCOLIDX = 0;
	private final static int PODCASTCOLIDX = 8;
	private final static int BOOKMARKCOLIDX = 9;
	private BroadcastReceiver mUnmountReceiver = null;
	private WakeLock mWakeLock;
	private int mServiceStartId = -1;
	private boolean mServiceInUse = false;
	private boolean mIsSupposedToBePlaying = false;
	private boolean mQuietMode = false;
	private AudioManager mAudioManager;
	private boolean mQueueIsSaveable = true;
	// used to track what type of audio focus loss caused the playback to pause
	private boolean mPausedByTransientLossOfFocus = false;

	// Flip action
	public static int ROLL_LOVER = -25;
	public static int ROLL_UPER = 25;
	public static int PITCH_LOVER = -160;
	public static int PITCH_UPER = 160;
	// Sensitivity
	public static int FLIP_SENS = 0;
	public static double SHAKE_SENS = 0d;
	public static Shaker shaker;
	public static String shake_actions_db;
	private IMediaPlaybackService mService = null;
	// Flip
	private SensorManager sensorMan = null;
	private float PITCH;
	private float ROLL;
	private boolean IsWorked = false;
	// Wallpaper Bitmap
	private Bitmap bgBitmap = null;

	private SharedPreferences mPreferences;
	// We use this to distinguish between different cards when saving/restoring
	// playlists.
	// This will have to change if we want to support multiple simultaneous
	// cards.
	private int mCardId;

	private MediaAppWidgetProvider4x1 mAppWidgetProvider4x1 = MediaAppWidgetProvider4x1
			.getInstance();
	private MediaAppWidgetProvider4x2 mAppWidgetProvider4x2 = MediaAppWidgetProvider4x2
			.getInstance();
	private MediaAppWidgetProvider1x1 mAppWidgetProvider1x1 = MediaAppWidgetProvider1x1
			.getInstance();
	private MediaAppWidgetProvider3x1 mAppWidgetProvider3x1 = MediaAppWidgetProvider3x1
			.getInstance();

	// interval after which we stop the service when idle
	private static final int IDLE_DELAY = 6000;

	// used to track current volume
	private float mCurrentVolume = 1.0f;

	private RemoteControlClient mRemoteControlClient;
	private Timer timer = new Timer();

	private Handler mMediaplayerHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			MusicUtils
					.debugLog("mMediaplayerHandler.handleMessage " + msg.what);
			switch (msg.what) {
			case FADEDOWN:
				mCurrentVolume -= .05f;
				if (mCurrentVolume > .2f) {
					mMediaplayerHandler.sendEmptyMessageDelayed(FADEDOWN, 10);
				} else {
					mCurrentVolume = .2f;
				}
				mPlayer.setVolume(mCurrentVolume);
				break;
			case FADEUP:
				mCurrentVolume += .01f;
				if (mCurrentVolume < 1.0f) {
					mMediaplayerHandler.sendEmptyMessageDelayed(FADEUP, 10);
				} else {
					mCurrentVolume = 1.0f;
				}
				mPlayer.setVolume(mCurrentVolume);
				break;
			case SERVER_DIED:
				if (mIsSupposedToBePlaying) {
					next(true);
				} else {
					// the server died when we were idle, so just
					// reopen the same song (it will start again
					// from the beginning though when the user
					// restarts)
					openCurrent();
				}
				break;
			case TRACK_ENDED:
				if (mRepeatMode == REPEAT_CURRENT) {
					seek(0);
					play();
				} else {
					next(false);
				}
				break;
			case RELEASE_WAKELOCK:
				mWakeLock.release();
				break;

			case FOCUSCHANGE:
				// This code is here so we can better synchronize it with the
				// code that
				// handles fade-in
				switch (msg.arg1) {
				case AudioManager.AUDIOFOCUS_LOSS:
					Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS");
					if (isPlaying()) {
						mPausedByTransientLossOfFocus = false;
					}
					pause();
					break;
				case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
					mMediaplayerHandler.removeMessages(FADEUP);
					mMediaplayerHandler.sendEmptyMessage(FADEDOWN);
					break;
				case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
					Log.v(LOGTAG,
							"AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT");
					if (isPlaying()) {
						SharedPreferences preferences = getSharedPreferences(
								MusicSettingsActivity.PREFERENCES_FILE,
								MODE_PRIVATE);

						int duckAttenuationdB = Integer
								.valueOf(preferences
										.getString(
												MusicSettingsActivity.KEY_DUCK_ATTENUATION_DB,
												MusicSettingsActivity.DEFAULT_DUCK_ATTENUATION_DB));
						// Convert from decibels to volume level
						float duckVolume = (float) Math.pow(10.0,
								-duckAttenuationdB / 20.0);
						Log.v(LOGTAG, "New attentuated volume: " + duckVolume);
						mPlayer.setVolume(duckVolume);
					} else {
						mPausedByTransientLossOfFocus = true;
						pause(); // don't move pause out because we have
									// ducking

					}

					break;
				case AudioManager.AUDIOFOCUS_GAIN:
					Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_GAIN");
					if (isPlaying() || mPausedByTransientLossOfFocus) {
						mPausedByTransientLossOfFocus = false;
						mCurrentVolume = 0f;
						mPlayer.setVolume(mCurrentVolume);
						play(); // also queues a fade-in
					} else {
						mMediaplayerHandler.removeMessages(FADEDOWN);
						mMediaplayerHandler.sendEmptyMessage(FADEUP);
					}
					break;
				default:
					Log.e(LOGTAG, "Unknown audio focus change code");
				}
				break;

			default:
				break;
			}
		}
	};
	private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			String cmd = intent.getStringExtra("command");
			MusicUtils.debugLog("mIntentReceiver.onReceive " + action + " / "
					+ cmd);
			if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
				next(true);
			} else if (CMDPREVIOUS.equals(cmd)
					|| PREVIOUS_ACTION.equals(action)) {
				prev();
			} else if (CMDTOGGLEPAUSEDUMMY.equals(cmd)
					|| TOGGLEPAUSE_ACTIONDUMMY.equals(action)) {
				if (isPlaying()) {
					pauseDummy();
					mPausedByTransientLossOfFocus = false;
				} else {
					play();
				}
			} else if (CMDTOGGLEPAUSE.equals(cmd)
					|| TOGGLEPAUSE_ACTION.equals(action)) {
				if (isPlaying()) {
					pause();
					mPausedByTransientLossOfFocus = false;
				} else {
					play();
				}
			} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
				pause();
				mPausedByTransientLossOfFocus = false;
			} else if (CMDPLAY.equals(cmd)) {
				play();
			} else if (CMDSTOP.equals(cmd)) {
				pause();
				mPausedByTransientLossOfFocus = false;
				seek(0);
			} else if (CMDCYCLEREPEAT.equals(cmd)
					|| CYCLEREPEAT_ACTION.equals(action)) {
				cycleRepeat();
			} else if (CMDTOGGLESHUFFLE.equals(cmd)
					|| TOGGLESHUFFLE_ACTION.equals(action)) {
				toggleShuffle();
			} else if (MediaAppWidgetProvider4x1.CMDAPPWIDGETUPDATE.equals(cmd)) {
				// Someone asked us to refresh a set of specific widgets,
				// probably
				// because they were just added.
				int[] appWidgetIds = intent
						.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
				mAppWidgetProvider4x1.performUpdate(MediaPlaybackService.this,
						appWidgetIds);
			} else if (MediaAppWidgetProvider4x2.CMDAPPWIDGETUPDATE.equals(cmd)) {
				// Someone asked us to refresh a set of specific widgets,
				// probably
				// because they were just added.
				int[] appWidgetIds = intent
						.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
				mAppWidgetProvider4x2.performUpdate(MediaPlaybackService.this,
						appWidgetIds);
			} else if (MediaAppWidgetProvider1x1.CMDAPPWIDGETUPDATE.equals(cmd)) {
				// Someone asked us to refresh a set of specific widgets,
				// probably
				// because they were just added.
				int[] appWidgetIds = intent
						.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
				mAppWidgetProvider1x1.performUpdate(MediaPlaybackService.this,
						appWidgetIds);
			} else if (MediaAppWidgetProvider3x1.CMDAPPWIDGETUPDATE.equals(cmd)) {
				// Someone asked us to refresh a set of specific widgets,
				// probably
				// because they were just added.
				int[] appWidgetIds = intent
						.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
				mAppWidgetProvider3x1.performUpdate(MediaPlaybackService.this,
						appWidgetIds);
			}
		}
	};

	private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
		public void onAudioFocusChange(int focusChange) {
			mMediaplayerHandler.obtainMessage(FOCUSCHANGE, focusChange, 0)
					.sendToTarget();
		}
	};
	private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				Log.v(LOGTAG, "PhoneState: received CALL_STATE_RINGING");
				if (isPlaying()) {
					mPausedByTransientLossOfFocus = true;
					pause();
				}
				break;

			case TelephonyManager.CALL_STATE_OFFHOOK:
				Log.v(LOGTAG, "PhoneState: received CALL_STATE_OFFHOOK");
				mPausedByTransientLossOfFocus = false;
				if (isPlaying()) {
					pause();
				}
				break;
			}
		}
	};

	public MediaPlaybackService() {
	}

	@Override
	public void onCreate() {
		super.onCreate();

		SharedPreferences mPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);

		Double shakeChange = new Double(mPrefs.getInt(
				MusicSettingsActivity.SHAKE_SENSITIVITY,
				(int) (MusicSettingsActivity.DEFAULT_SHAKE_SENS)));

		SHAKE_SENS = shakeChange;

		if (SHAKE_SENS == 0) {
			new Shaker(this, 1.25, 500, this);
		} else {
			new Shaker(this, SHAKE_SENS + .25d, 500, this);
		}

		// Flip action
		sensorMan = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		sensorMan.registerListener(this,
				sensorMan.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_UI);

		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		ComponentName rec = new ComponentName(getPackageName(),
				MediaButtonIntentReceiver.class.getName());
		mAudioManager.registerMediaButtonEventReceiver(rec);
		Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
		mediaButtonIntent.setComponent(rec);
		PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(
				getApplicationContext(), 0, mediaButtonIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);
		mRemoteControlClient = new RemoteControlClient(mediaPendingIntent);

		int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
				| RemoteControlClient.FLAG_KEY_MEDIA_NEXT
				| RemoteControlClient.FLAG_KEY_MEDIA_PLAY
				| RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
				| RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
				| RemoteControlClient.FLAG_KEY_MEDIA_STOP;
		mRemoteControlClient.setTransportControlFlags(flags);

		mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE
				| MODE_WORLD_WRITEABLE);

		SharedPreferences preferences = getSharedPreferences(
				MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);

		if (preferences.getBoolean(MusicSettingsActivity.KEY_LOCK, true)) {
			mAudioManager.registerRemoteControlClient(mRemoteControlClient);
		}
		mCardId = MusicUtils.getCardId(this);

		registerExternalStorageListener();

		// Needs to be done in this thread, since otherwise
		// ApplicationContext.getPowerManager() crashes.
		mPlayer = new MultiPlayer();
		mPlayer.setHandler(mMediaplayerHandler);

		reloadQueue();
		notifyChange(QUEUE_CHANGED);
		notifyChange(META_CHANGED);

		IntentFilter commandFilter = new IntentFilter();
		commandFilter.addAction(SERVICECMD);
		commandFilter.addAction(TOGGLEPAUSE_ACTION);
		commandFilter.addAction(TOGGLEPAUSE_ACTIONDUMMY);
		commandFilter.addAction(PAUSE_ACTION);
		commandFilter.addAction(NEXT_ACTION);
		commandFilter.addAction(PREVIOUS_ACTION);
		commandFilter.addAction(CYCLEREPEAT_ACTION);
		commandFilter.addAction(TOGGLESHUFFLE_ACTION);
		commandFilter.addAction(PLAYSTATUS_REQUEST);
		registerReceiver(mIntentReceiver, commandFilter);

		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
				.getClass().getName());
		mWakeLock.setReferenceCounted(false);

		// If the service was idle, but got killed before it stopped itself, the
		// system will relaunch it. Make sure it gets stopped again in that
		// case.
		Message msg = mDelayedStopHandler.obtainMessage();
		mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
	}

	@Override
	public void onDestroy() {
		sensorMan.unregisterListener(this);

		if (shaker != null)
			shaker.close();
		shaker = null;

		// Check that we're not being destroyed while something is still
		// playing.
		if (isPlaying()) {
			Log.e(LOGTAG, "Service being destroyed while still playing.");
		}
		// release all MediaPlayer resources, including the native player and
		// wakelocks
		Intent i = new Intent(
				AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION);
		i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
		i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
		sendBroadcast(i);
		mPlayer.release();
		mPlayer = null;

		mAudioManager.abandonAudioFocus(mAudioFocusListener);
		mAudioManager.unregisterRemoteControlClient(mRemoteControlClient);

		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		telephonyManager.listen(mPhoneStateListener,
				PhoneStateListener.LISTEN_NONE);

		// make sure there aren't any other messages coming
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		mMediaplayerHandler.removeCallbacksAndMessages(null);

		if (mCursor != null) {
			mCursor.close();
			mCursor = null;
		}

		unregisterReceiver(mIntentReceiver);
		if (mUnmountReceiver != null) {
			unregisterReceiver(mUnmountReceiver);
			mUnmountReceiver = null;
		}
		mWakeLock.release();
		super.onDestroy();
	}

	private final char hexdigits[] = new char[] { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	private void saveQueue(boolean full) {
		if (!mQueueIsSaveable) {
			return;
		}

		Editor ed = mPreferences.edit();
		// long start = System.currentTimeMillis();
		if (full) {
			StringBuilder q = new StringBuilder();

			// The current playlist is saved as a list of "reverse hexadecimal"
			// numbers, which we can generate faster than normal decimal or
			// hexadecimal numbers, which in turn allows us to save the playlist
			// more often without worrying too much about performance.
			// (saving the full state takes about 40 ms under no-load conditions
			// on the phone)
			int len = mPlayListLen;
			for (int i = 0; i < len; i++) {
				long n = mPlayList[i];
				if (n < 0) {
					continue;
				} else if (n == 0) {
					q.append("0;");
				} else {
					while (n != 0) {
						int digit = (int) (n & 0xf);
						n >>>= 4;
						q.append(hexdigits[digit]);
					}
					q.append(";");
				}
			}
			// Log.i("@@@@ service", "created queue string in " +
			// (System.currentTimeMillis() - start) + " ms");
			ed.putString("queue", q.toString());
			ed.putInt("cardid", mCardId);
			if (mShuffleMode != SHUFFLE_NONE) {
				// In shuffle mode we need to save the history too
				len = mHistory.size();
				q.setLength(0);
				for (int i = 0; i < len; i++) {
					int n = mHistory.get(i);
					if (n == 0) {
						q.append("0;");
					} else {
						while (n != 0) {
							int digit = (n & 0xf);
							n >>>= 4;
							q.append(hexdigits[digit]);
						}
						q.append(";");
					}
				}
				ed.putString("history", q.toString());
			}
		}
		ed.putInt("curpos", mPlayPos);
		if (mPlayer.isInitialized()) {
			ed.putLong("seekpos", mPlayer.position());
		}
		ed.putInt("repeatmode", mRepeatMode);
		ed.putInt("shufflemode", mShuffleMode);
		SharedPreferencesCompat.apply(ed);

		// Log.i("@@@@ service", "saved state in " + (System.currentTimeMillis()
		// - start) + " ms");
	}

	private void reloadQueue() {
		String q = null;

		int id = mCardId;
		if (mPreferences.contains("cardid")) {
			id = mPreferences.getInt("cardid", ~mCardId);
		}
		if (id == mCardId) {
			// Only restore the saved playlist if the card is still
			// the same one as when the playlist was saved
			q = mPreferences.getString("queue", "");
		}
		int qlen = q != null ? q.length() : 0;
		if (qlen > 1) {
			// Log.i("@@@@ service", "loaded queue: " + q);
			int plen = 0;
			int n = 0;
			int shift = 0;
			for (int i = 0; i < qlen; i++) {
				char c = q.charAt(i);
				if (c == ';') {
					ensurePlayListCapacity(plen + 1);
					mPlayList[plen] = n;
					plen++;
					n = 0;
					shift = 0;
				} else {
					if (c >= '0' && c <= '9') {
						n += ((c - '0') << shift);
					} else if (c >= 'a' && c <= 'f') {
						n += ((10 + c - 'a') << shift);
					} else {
						// bogus playlist data
						plen = 0;
						break;
					}
					shift += 4;
				}
			}
			mPlayListLen = plen;

			int pos = mPreferences.getInt("curpos", 0);
			if (pos < 0 || pos >= mPlayListLen) {
				// The saved playlist is bogus, discard it
				mPlayListLen = 0;
				return;
			}
			mPlayPos = pos;

			// When reloadQueue is called in response to a card-insertion,
			// we might not be able to query the media provider right away.
			// To deal with this, try querying for the current file, and if
			// that fails, wait a while and try again. If that too fails,
			// assume there is a problem and don't restore the state.
			Cursor crsr = MusicUtils.query(this,
					MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
					new String[] { "_id" }, "_id=" + mPlayList[mPlayPos], null,
					null);
			if (crsr == null || crsr.getCount() == 0) {
				// wait a bit and try again
				SystemClock.sleep(3000);
				crsr = getContentResolver().query(
						MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
						mCursorCols, "_id=" + mPlayList[mPlayPos], null, null);
			}
			if (crsr != null) {
				crsr.close();
			}

			// Make sure we don't auto-skip to the next song, since that
			// also starts playback. What could happen in that case is:
			// - music is paused
			// - go to UMS and delete some files, including the currently
			// playing one
			// - come back from UMS
			// (time passes)
			// - music app is killed for some reason (out of memory)
			// - music service is restarted, service restores state, doesn't
			// find
			// the "current" file, goes to the next and: playback starts on its
			// own, potentially at some random inconvenient time.
			mOpenFailedCounter = 20;
			mQuietMode = true;
			openCurrent();
			mQuietMode = false;
			if (!mPlayer.isInitialized()) {
				// couldn't restore the saved state
				mPlayListLen = 0;
				return;
			}

			long seekpos = mPreferences.getLong("seekpos", 0);
			seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
			Log.d(LOGTAG, "restored queue, currently at position " + position()
					+ "/" + duration() + " (requested " + seekpos + ")");

			int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
			if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
				repmode = REPEAT_NONE;
			}
			mRepeatMode = repmode;

			int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
			if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
				shufmode = SHUFFLE_NONE;
			}
			if (shufmode != SHUFFLE_NONE) {
				// in shuffle mode we need to restore the history too
				q = mPreferences.getString("history", "");
				qlen = q != null ? q.length() : 0;
				if (qlen > 1) {
					plen = 0;
					n = 0;
					shift = 0;
					mHistory.clear();
					for (int i = 0; i < qlen; i++) {
						char c = q.charAt(i);
						if (c == ';') {
							if (n >= mPlayListLen) {
								// bogus history data
								mHistory.clear();
								break;
							}
							mHistory.add(n);
							n = 0;
							shift = 0;
						} else {
							if (c >= '0' && c <= '9') {
								n += ((c - '0') << shift);
							} else if (c >= 'a' && c <= 'f') {
								n += ((10 + c - 'a') << shift);
							} else {
								// bogus history data
								mHistory.clear();
								break;
							}
							shift += 4;
						}
					}
				}
			}
			if (shufmode == SHUFFLE_AUTO) {
				if (!makeAutoShuffleList()) {
					shufmode = SHUFFLE_NONE;
				}
			}
			mShuffleMode = shufmode;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		mServiceInUse = true;
		return mBinder;
	}

	@Override
	public void onRebind(Intent intent) {
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		mServiceInUse = true;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mServiceStartId = startId;
		mDelayedStopHandler.removeCallbacksAndMessages(null);

		if (intent != null) {
			String action = intent.getAction();
			String cmd = intent.getStringExtra("command");
			MusicUtils.debugLog("onStartCommand " + action + " / " + cmd);

			if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
				next(true);
			} else if (CMDPREVIOUS.equals(cmd)
					|| PREVIOUS_ACTION.equals(action)) {
				if (position() < 2000) {
					prev();
				} else {
					seek(0);
					play();
				}
			} else if (CMDTOGGLEPAUSEDUMMY.equals(cmd)
					|| TOGGLEPAUSE_ACTIONDUMMY.equals(action)) {
				if (isPlaying()) {
					pauseDummy();
					mPausedByTransientLossOfFocus = false;
				} else {
					play();
				}
			} else if (CMDTOGGLEPAUSE.equals(cmd)
					|| TOGGLEPAUSE_ACTION.equals(action)) {
				if (isPlaying()) {
					pause();
					mPausedByTransientLossOfFocus = false;
				} else {
					play();
				}
			} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
				pause();
				mPausedByTransientLossOfFocus = false;
			} else if (CMDPLAY.equals(cmd)) {
				play();
			} else if (CMDSTOP.equals(cmd)) {
				pause();
				stopForeground(true);
				mPausedByTransientLossOfFocus = false;
				seek(0);
			} else if (CMDCYCLEREPEAT.equals(cmd)
					|| CYCLEREPEAT_ACTION.equals(action)) {
				cycleRepeat();
			} else if (CMDTOGGLESHUFFLE.equals(cmd)
					|| TOGGLESHUFFLE_ACTION.equals(action)) {
				toggleShuffle();
			} else if (PLAYSTATUS_REQUEST.equals(action)) {
				notifyChange(PLAYSTATUS_RESPONSE);
			}
		}

		// make sure the service will shut down on its own if it was
		// just started but not bound to and nothing is playing
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		Message msg = mDelayedStopHandler.obtainMessage();
		mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
		return START_STICKY;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		mServiceInUse = false;

		// Take a snapshot of the current playlist
		saveQueue(true);

		if (isPlaying() || mPausedByTransientLossOfFocus) {
			// something is currently playing, or will be playing once
			// an in-progress action requesting audio focus ends, so don't stop
			// the service now.
			return true;
		}

		// If there is a playlist but playback is paused, then wait a while
		// before stopping the service, so that pause/resume isn't slow.
		// Also delay stopping the service if we're transitioning between
		// tracks.
		if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
			Message msg = mDelayedStopHandler.obtainMessage();
			mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
			return true;
		}

		// No active playlist, OK to stop the service right now
		stopSelf(mServiceStartId);
		return true;
	}

	private Handler mDelayedStopHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// Check again to make sure nothing is playing right now
			if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse
					|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
				return;
			}
			// save the queue again, because it might have changed
			// since the user exited the music app (because of
			// party-shuffle or because the play-position changed)
			saveQueue(true);
			stopSelf(mServiceStartId);
		}
	};

	/**
	 * Called when we receive a ACTION_MEDIA_EJECT notification.
	 * 
	 * @param storagePath
	 *            path to mount point for the removed media
	 */
	public void closeExternalStorageFiles(String storagePath) {
		// stop playback and clean up if the SD card is going to be unmounted.
		stop(true);
		notifyChange(QUEUE_CHANGED);
		notifyChange(META_CHANGED);
	}

	/**
	 * Registers an intent to listen for ACTION_MEDIA_EJECT notifications. The
	 * intent will call closeExternalStorageFiles() if the external media is
	 * going to be ejected, so applications can clean up any files they have
	 * open.
	 */
	public void registerExternalStorageListener() {
		if (mUnmountReceiver == null) {
			mUnmountReceiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {
					String action = intent.getAction();
					if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
						saveQueue(true);
						mQueueIsSaveable = false;
						closeExternalStorageFiles(intent.getData().getPath());
					} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
						mMediaMountedCount++;
						mCardId = MusicUtils
								.getCardId(MediaPlaybackService.this);
						reloadQueue();
						mQueueIsSaveable = true;
						notifyChange(QUEUE_CHANGED);
						notifyChange(META_CHANGED);
					}
				}
			};
			IntentFilter iFilter = new IntentFilter();
			iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
			iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
			iFilter.addDataScheme("file");
			registerReceiver(mUnmountReceiver, iFilter);
		}
	}

	// Set Custom Background Image
	public void setCustomBackground() {

		SharedPreferences preferences = getSharedPreferences(
				MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);

		mPreferences.getBoolean(MusicSettingsActivity.KEY_ENABLE_HOME_ART,
				false);

		// First clean our old data
		if (bgBitmap != null) {
			bgBitmap.recycle();
			bgBitmap = null;
			System.gc();
		}
		// now load the proper bg
		String BG_FILE = getFilesDir().toString() + File.separator
				+ MusicSettingsActivity.BG_PHOTO_FILE;
		bgBitmap = BitmapFactory.decodeFile(BG_FILE);

		try {
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_HOME_ART, false)) {
				WallpaperManager.getInstance(this).setBitmap(bgBitmap);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// Set launcher wallpaper as album art
	private void setArtwork() {
		SharedPreferences preferences = getSharedPreferences(
				MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);

		mPreferences.getBoolean(MusicSettingsActivity.KEY_ENABLE_HOME_ART,
				false);
		Bitmap b = MusicUtils
				.getArtwork(this, getAudioId(), getAlbumId(), true);
		try {
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_HOME_ART, false)) {
				WallpaperManager.getInstance(this).setBitmap(b);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Notify the change-receivers that something has changed. The intent that
	 * is sent contains the following data for the currently playing track: "id"
	 * - Integer: the database row ID "artist" - String: the name of the artist
	 * "album" - String: the name of the album "track" - String: the name of the
	 * track The intent has an action that is one of
	 * "com.android.music.metachanged" "com.android.music.queuechanged",
	 * "com.android.music.playbackcomplete" "com.android.music.playstatechanged"
	 * respectively indicating that a new track has started playing, that the
	 * playback queue has changed, that playback has stopped because the last
	 * file in the list has been played, or that the play-state changed
	 * (paused/resumed).
	 */
	private void notifyChange(String what) {

		Intent i = new Intent(what);
		i.putExtra("id", Long.valueOf(getAudioId()));
		i.putExtra("artist", getArtistName());
		i.putExtra("album", getAlbumName());
		i.putExtra("track", getTrackName());
		i.putExtra("playing", isPlaying());
		i.putExtra("pos", position());
		i.putExtra("dur", duration());
		i.putExtra("albumLong", getAlbumId());
		i.putExtra("trackLong", getAudioId());
		if (mPlayList != null)
			i.putExtra("ListSize", Long.valueOf(mPlayList.length));
		else
			i.putExtra("ListSize", Long.valueOf(mPlayListLen));
		sendStickyBroadcast(i);
		if (what.equals(PLAYSTATE_CHANGED)) {
			mRemoteControlClient
					.setPlaybackState(isPlaying() ? RemoteControlClient.PLAYSTATE_PLAYING
							: RemoteControlClient.PLAYSTATE_PAUSED);
		} else if (what.equals(META_CHANGED)) {
			Bitmap b = MusicUtils.getArtwork(this, getAudioId(), getAlbumId(),
					true);
			RemoteControlClient.MetadataEditor ed = mRemoteControlClient
					.editMetadata(true);
			ed.putString(MediaMetadataRetriever.METADATA_KEY_TITLE,
					getTrackName());
			ed.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM,
					getAlbumName());
			ed.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST,
					getArtistName());
			ed.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, duration());

			ed.putBitmap(MetadataEditor.BITMAP_KEY_ARTWORK, b);

			ed.apply();
		}
		if (what.equals(QUEUE_CHANGED)) {
			saveQueue(true);
		} else {
			saveQueue(false);
		}

		// Share this notification directly with our widgets
		mAppWidgetProvider4x1.notifyChange(this, what);
		mAppWidgetProvider4x2.notifyChange(this, what);
		mAppWidgetProvider1x1.notifyChange(this, what);
		mAppWidgetProvider3x1.notifyChange(this, what);
	}

	private void ensurePlayListCapacity(int size) {
		if (mPlayList == null || size > mPlayList.length) {
			// reallocate at 2x requested size so we don't
			// need to grow and copy the array for every
			// insert
			long[] newlist = new long[size * 2];
			int len = mPlayList != null ? mPlayList.length : mPlayListLen;
			for (int i = 0; i < len; i++) {
				newlist[i] = mPlayList[i];
			}
			mPlayList = newlist;
		}
		// FIXME: shrink the array when the needed size is much smaller
		// than the allocated size
	}

	// insert the list of songs at the specified position in the playlist
	private void addToPlayList(long[] list, int position) {
		int addlen = list.length;
		if (position < 0) { // overwrite
			mPlayListLen = 0;
			position = 0;
		}
		ensurePlayListCapacity(mPlayListLen + addlen);
		if (position > mPlayListLen) {
			position = mPlayListLen;
		}

		// move part of list after insertion point
		int tailsize = mPlayListLen - position;
		for (int i = tailsize; i > 0; i--) {
			mPlayList[position + i] = mPlayList[position + i - addlen];
		}

		// copy list into playlist
		for (int i = 0; i < addlen; i++) {
			mPlayList[position + i] = list[i];
		}
		mPlayListLen += addlen;
		if (mPlayListLen == 0) {
			mCursor.close();
			mCursor = null;
			notifyChange(META_CHANGED);
		}
	}

	/**
	 * Appends a list of tracks to the current playlist. If nothing is playing
	 * currently, playback will be started at the first track. If the action is
	 * NOW, playback will switch to the first of the new tracks immediately.
	 * 
	 * @param list
	 *            The list of tracks to append.
	 * @param action
	 *            NOW, NEXT or LAST
	 */
	public void enqueue(long[] list, int action) {
		synchronized (this) {
			if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
				addToPlayList(list, mPlayPos + 1);
				notifyChange(QUEUE_CHANGED);
			} else {
				// action == LAST || action == NOW || mPlayPos + 1 ==
				// mPlayListLen
				addToPlayList(list, Integer.MAX_VALUE);
				notifyChange(QUEUE_CHANGED);
				if (action == NOW) {
					mPlayPos = mPlayListLen - list.length;
					openCurrent();
					play();
					notifyChange(META_CHANGED);
					return;
				}
			}
			if (mPlayPos < 0) {
				mPlayPos = 0;
				openCurrent();
				play();
				notifyChange(META_CHANGED);
			}
		}
	}

	/**
	 * Replaces the current playlist with a new list, and prepares for starting
	 * playback at the specified position in the list, or a random position if
	 * the specified position is 0.
	 * 
	 * @param list
	 *            The new list of tracks.
	 */
	public void open(long[] list, int position) {
		synchronized (this) {
			if (mShuffleMode == SHUFFLE_AUTO) {
				mShuffleMode = SHUFFLE_NORMAL;
			}
			long oldId = getAudioId();
			int listlength = list.length;
			boolean newlist = true;
			if (mPlayListLen == listlength) {
				// possible fast path: list might be the same
				newlist = false;
				for (int i = 0; i < listlength; i++) {
					if (list[i] != mPlayList[i]) {
						newlist = true;
						break;
					}
				}
			}
			if (newlist) {
				addToPlayList(list, -1);
				notifyChange(QUEUE_CHANGED);
			}
			if (position >= 0) {
				mPlayPos = position;
			} else {
				mPlayPos = mRand.nextInt(mPlayListLen);
			}
			mHistory.clear();

			saveBookmarkIfNeeded();
			openCurrent();
			if (oldId != getAudioId()) {
				notifyChange(META_CHANGED);
			}
		}
	}

	/**
	 * Moves the item at index1 to index2.
	 * 
	 * @param index1
	 * @param index2
	 */
	public void moveQueueItem(int index1, int index2) {
		synchronized (this) {
			if (index1 >= mPlayListLen) {
				index1 = mPlayListLen - 1;
			}
			if (index2 >= mPlayListLen) {
				index2 = mPlayListLen - 1;
			}
			if (index1 < index2) {
				long tmp = mPlayList[index1];
				for (int i = index1; i < index2; i++) {
					mPlayList[i] = mPlayList[i + 1];
				}
				mPlayList[index2] = tmp;
				if (mPlayPos == index1) {
					mPlayPos = index2;
				} else if (mPlayPos >= index1 && mPlayPos <= index2) {
					mPlayPos--;
				}
			} else if (index2 < index1) {
				long tmp = mPlayList[index1];
				for (int i = index1; i > index2; i--) {
					mPlayList[i] = mPlayList[i - 1];
				}
				mPlayList[index2] = tmp;
				if (mPlayPos == index1) {
					mPlayPos = index2;
				} else if (mPlayPos >= index2 && mPlayPos <= index1) {
					mPlayPos++;
				}
			}
			notifyChange(QUEUE_CHANGED);
		}
	}

	/**
	 * Returns the current play list
	 * 
	 * @return An array of integers containing the IDs of the tracks in the play
	 *         list
	 */
	public long[] getQueue() {
		synchronized (this) {
			int len = mPlayListLen;
			long[] list = new long[len];
			for (int i = 0; i < len; i++) {
				list[i] = mPlayList[i];
			}
			return list;
		}
	}

	private void openCurrent() {
		synchronized (this) {
			if (mCursor != null) {
				mCursor.close();
				mCursor = null;
			}

			if (mPlayListLen == 0) {
				return;
			}
			stop(false);

			String id = String.valueOf(mPlayList[mPlayPos]);

			mCursor = getContentResolver().query(
					MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursorCols,
					"_id=" + id, null, null);
			if (mCursor != null) {
				mCursor.moveToFirst();
				open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id);
				// go to bookmark if needed
				if (isPodcast()) {
					long bookmark = getBookmark();
					// Start playing a little bit before the bookmark,
					// so it's easier to get back in to the narrative.
					seek(bookmark - 5000);
				}
			}
		}
	}

	/**
	 * Opens the specified file and readies it for playback.
	 * 
	 * @param path
	 *            The full path of the file to be opened.
	 */
	public void open(String path) {
		synchronized (this) {
			if (path == null) {
				return;
			}

			// if mCursor is null, try to associate path with a database cursor
			if (mCursor == null) {

				ContentResolver resolver = getContentResolver();
				Uri uri;
				String where;
				String selectionArgs[];
				if (path.startsWith("content://media/")) {
					uri = Uri.parse(path);
					where = null;
					selectionArgs = null;
				} else {
					uri = MediaStore.Audio.Media.getContentUriForPath(path);
					where = MediaStore.Audio.Media.DATA + "=?";
					selectionArgs = new String[] { path };
				}

				try {
					mCursor = resolver.query(uri, mCursorCols, where,
							selectionArgs, null);
					if (mCursor != null) {
						if (mCursor.getCount() == 0) {
							mCursor.close();
							mCursor = null;
						} else {
							mCursor.moveToNext();
							ensurePlayListCapacity(1);
							mPlayListLen = 1;
							mPlayList[0] = mCursor.getLong(IDCOLIDX);
							mPlayPos = 0;
						}
					}
				} catch (UnsupportedOperationException ex) {
				}
			}
			mFileToPlay = path;
			mPlayer.setDataSource(mFileToPlay);
			if (!mPlayer.isInitialized()) {
				stop(true);
				if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
					// beware: this ends up being recursive because next() calls
					// open() again.
					next(false);
				}
				if (!mPlayer.isInitialized() && mOpenFailedCounter != 0) {
					// need to make sure we only shows this once
					mOpenFailedCounter = 0;
					if (!mQuietMode) {
						Toast.makeText(this, R.string.playback_failed,
								Toast.LENGTH_SHORT).show();
					}
					Log.d(LOGTAG, "Failed to open file for playback");
				}
				startProgressUpdate();
			} else {
				mOpenFailedCounter = 0;
			}
		}
	}

	/**
	 * Starts playback of a previously opened file.
	 */
	public void play() {

		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		if (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
			return;
		}
		startProgressUpdate();
		setArtwork();

		mAudioManager.requestAudioFocus(mAudioFocusListener,
				AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
		mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this
				.getPackageName(), MediaButtonIntentReceiver.class.getName()));

		telephonyManager.listen(mPhoneStateListener,
				PhoneStateListener.LISTEN_CALL_STATE);

		if (mPlayer.isInitialized()) {
			// if we are at the end of the song, go to the next song first
			long duration = mPlayer.duration();
			if (mRepeatMode != REPEAT_CURRENT && duration > 2000
					&& mPlayer.position() >= duration - 2000) {
				next(true);
			}

			mPlayer.start();
			// make sure we fade in, in case a previous fadein was stopped
			// because
			// of another focus loss
			mMediaplayerHandler.removeMessages(FADEDOWN);
			mMediaplayerHandler.sendEmptyMessage(FADEUP);
			RemoteViews views = new RemoteViews(getPackageName(),
					R.layout.statusbar);
			views.setImageViewBitmap(R.id.icon, MusicUtils.getArtwork(
					getBaseContext(), getAudioId(), getAlbumId(), true));
			ComponentName rec = new ComponentName(getPackageName(),
					MediaButtonIntentReceiver.class.getName());
			Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
			mediaButtonIntent.putExtra(CMDNOTIF, 1);
			mediaButtonIntent.setComponent(rec);
			KeyEvent mediaKey = new KeyEvent(KeyEvent.ACTION_DOWN,
					KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
			mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, mediaKey);
			PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(
					getApplicationContext(), 1, mediaButtonIntent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			mediaButtonIntent.putExtra(CMDNOTIF, 2);
			mediaKey = new KeyEvent(KeyEvent.ACTION_DOWN,
					KeyEvent.KEYCODE_MEDIA_NEXT);
			mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, mediaKey);
			mediaPendingIntent = PendingIntent.getBroadcast(
					getApplicationContext(), 2, mediaButtonIntent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			views.setOnClickPendingIntent(R.id.status_media_next,
					mediaPendingIntent);
			mediaButtonIntent.putExtra(CMDNOTIF, 3);
			mediaKey = new KeyEvent(KeyEvent.ACTION_DOWN,
					KeyEvent.KEYCODE_MEDIA_STOP);
			mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, mediaKey);
			mediaPendingIntent = PendingIntent.getBroadcast(
					getApplicationContext(), 3, mediaButtonIntent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			views.setOnClickPendingIntent(R.id.status_media_collapse,
					mediaPendingIntent);
			views.setImageViewResource(R.id.status_media_play,
					R.drawable.status_pause);
			mediaButtonIntent.putExtra(CMDNOTIF, 4);
			mediaKey = new KeyEvent(KeyEvent.ACTION_DOWN,
					KeyEvent.KEYCODE_MEDIA_PREVIOUS);
			mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, mediaKey);
			mediaPendingIntent = PendingIntent.getBroadcast(
					getApplicationContext(), 4, mediaButtonIntent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			views.setOnClickPendingIntent(R.id.status_media_prev,
					mediaPendingIntent);
			linkButtons(this, views);

			SharedPreferences preferences = getSharedPreferences(
					MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
			mPreferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_NEXT_BUTTON, false);
			mPreferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_COLLAPSE, false);
			mPreferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_PREV_BUTTON, false);
			mPreferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_PLAY_BUTTON, false);
			mPreferences.getBoolean(MusicSettingsActivity.KEY_TICK, false);
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_PREV_BUTTON, false)) {

				views.setViewVisibility(R.id.status_media_prev, View.VISIBLE);
			} else {
				views.setViewVisibility(R.id.status_media_prev, View.GONE);
			}
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_PLAY_BUTTON, false)) {

				views.setViewVisibility(R.id.status_media_play, View.VISIBLE);
			} else {
				views.setViewVisibility(R.id.status_media_play, View.GONE);

			}
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_NEXT_BUTTON, false)) {

				views.setViewVisibility(R.id.status_media_next, View.VISIBLE);
			} else {
				views.setViewVisibility(R.id.status_media_next, View.GONE);

			}
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_COLLAPSE, false)) {

				views.setViewVisibility(R.id.status_media_collapse,
						View.VISIBLE);
			} else {
				views.setViewVisibility(R.id.status_media_collapse, View.GONE);

			}
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_SONG_TEXT, true)) {
				views.setViewVisibility(R.id.trackname, View.VISIBLE);
			} else {
				views.setViewVisibility(R.id.trackname, View.INVISIBLE);

			}
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_ARTIST_TEXT, true)) {
				views.setViewVisibility(R.id.artist, View.VISIBLE);
			} else {
				views.setViewVisibility(R.id.artist, View.GONE);

			}
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_ALBUM_TEXT, false)) {
				views.setViewVisibility(R.id.album, View.VISIBLE);
			} else {
				views.setViewVisibility(R.id.album, View.GONE);

			}
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_ALBUM_ART, true)) {
				views.setViewVisibility(R.id.icon, View.VISIBLE);
				views.setViewVisibility(R.id.status_icon, View.GONE);

			} else {
				views.setViewVisibility(R.id.icon, View.GONE);
				views.setViewVisibility(R.id.status_icon, View.VISIBLE);
				views.setImageViewResource(R.id.status_icon,
						R.drawable.stat_notify_musicplayer);

			}
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_NONYA, false)) {
				views.setViewVisibility(R.id.icon, View.GONE);
				views.setViewVisibility(R.id.status_icon, View.GONE);

			}

			SharedPreferences mPrefs = PreferenceManager
					.getDefaultSharedPreferences(this);

			int aColor = new Integer(mPrefs.getInt(
					MusicSettingsActivity.SCREENSAVER_COLOR_ALPHA,
					MusicSettingsActivity.DEFAULT_SCREENSAVER_COLOR_ALPHA));
			int rColor = new Integer(mPrefs.getInt(
					MusicSettingsActivity.SCREENSAVER_COLOR_RED,
					MusicSettingsActivity.DEFAULT_SCREENSAVER_COLOR_RED));
			int gColor = new Integer(mPrefs.getInt(
					MusicSettingsActivity.SCREENSAVER_COLOR_GREEN,
					MusicSettingsActivity.DEFAULT_SCREENSAVER_COLOR_GREEN));
			int bColor = new Integer(mPrefs.getInt(
					MusicSettingsActivity.SCREENSAVER_COLOR_BLUE,
					MusicSettingsActivity.DEFAULT_SCREENSAVER_COLOR_BLUE));

			int SCREEN_SAVER_COLOR_DIM = Color.argb(aColor, rColor, gColor,
					bColor);
			if (preferences.getBoolean(
					MusicSettingsActivity.KEY_ENABLE_STATUS_TEXT_COLOR, true)) {
				views.setTextColor(R.id.trackname, 0xFFFFFFFF);
				views.setTextColor(R.id.artist, 0xFF999999);
				views.setTextColor(R.id.album, 0xFF999999);
			} else {
				views.setTextColor(R.id.trackname, SCREEN_SAVER_COLOR_DIM);
				views.setTextColor(R.id.artist, SCREEN_SAVER_COLOR_DIM);
				views.setTextColor(R.id.album, SCREEN_SAVER_COLOR_DIM);

			}

			if (getAudioId() < 0) {
				// streaming
				views.setTextViewText(R.id.trackname, getPath());
				views.setTextViewText(R.id.artist, getPath());
				views.setTextViewText(R.id.album, getPath());
			} else {
				String artist = getArtistName();
				views.setTextViewText(R.id.trackname, getTrackName());
				views.setTextViewText(R.id.artist, getArtistName());
				views.setTextViewText(R.id.album, getAlbumName());
				if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
					artist = getString(R.string.unknown_artist_name);
				}
				String album = getAlbumName();
				if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
					album = getString(R.string.unknown_album_name);
				}
				String trackname = getTrackName();
				if (trackname == null
						|| album.equals(MediaStore.UNKNOWN_STRING)) {
					trackname = getString(R.string.unknown_album_name);
				}
			}

			status = new Notification();
			status.contentView = views;
			status.flags |= Notification.FLAG_ONGOING_EVENT;
			status.icon = R.drawable.stat_notify_musicplayer;
			if (preferences.getBoolean(MusicSettingsActivity.KEY_TICK, true)) {
				status.tickerText = getTrackName() + " by " + getArtistName();
			}
			status.contentIntent = PendingIntent.getActivity(this, 0,
					new Intent("com.android.music.PLAYBACK_VIEWER")
							.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
			startForeground(PLAYBACKSERVICE_STATUS, status);
			if (!mIsSupposedToBePlaying) {
				mIsSupposedToBePlaying = true;
				notifyChange(PLAYSTATE_CHANGED);
			}

		} else if (mPlayListLen <= 0) {
			// This is mostly so that if you press 'play' on a bluetooth headset
			// without every having played anything before, it will still play
			// something.
			setShuffleMode(SHUFFLE_AUTO);
		}
	}

	private void linkButtons(Context context, RemoteViews views) {
		// Connect up various buttons and touch events
		Intent intent;
		PendingIntent pendingIntent;

		final ComponentName serviceName = new ComponentName(context,
				MediaPlaybackService.class);

		intent = new Intent(MediaPlaybackService.TOGGLEPAUSE_ACTIONDUMMY);
		intent.setComponent(serviceName);
		pendingIntent = PendingIntent.getService(context,
				0 /* no requestCode */, intent, 0 /* no flags */);
		views.setOnClickPendingIntent(R.id.status_media_play, pendingIntent);

	}

	private void stop(boolean remove_status_icon) {
		if (mPlayer.isInitialized()) {
			mPlayer.stop();
		}
		mFileToPlay = null;
		if (mCursor != null) {
			mCursor.close();
			mCursor = null;
		}
		if (remove_status_icon) {
			gotoIdleState();
		} else {
			stopForeground(false);
		}
		if (remove_status_icon) {
			mIsSupposedToBePlaying = false;
		}
	}

	/**
	 * Stops playback.
	 */
	public void stop() {
		stop(true);
		stopProgressUpdate();
	}

	/**
	 * Pauses playback (call play() to resume)
	 */
	public void pause() {
		synchronized (this) {
			mMediaplayerHandler.removeMessages(FADEUP);
			if (isPlaying()) {
				mPlayer.pause();
				gotoIdleState();
				stopProgressUpdate();
				stopForeground(true);
				mIsSupposedToBePlaying = false;
				notifyChange(PLAYSTATE_CHANGED);
				saveBookmarkIfNeeded();
			}
		}
	}

	// This is so the notification won't clear immediately if you pause from the
	// status bar
	public void pauseDummy() {
		synchronized (this) {
			mMediaplayerHandler.removeMessages(FADEUP);
			if (isPlaying()) {
				mPlayer.pause();
				gotoIdleState();
				mIsSupposedToBePlaying = false;
				notifyChange(PLAYSTATE_CHANGED);
				saveBookmarkIfNeeded();
			}
		}
	}

	/**
	 * Returns whether something is currently playing
	 * 
	 * @return true if something is playing (or will be playing shortly, in case
	 *         we're currently transitioning between tracks), false if not.
	 */
	public boolean isPlaying() {
		return mIsSupposedToBePlaying;
	}

	/*
	 * Desired behavior for prev/next/shuffle:
	 * 
	 * - NEXT will move to the next track in the list when not shuffling, and to
	 * a track randomly picked from the not-yet-played tracks when shuffling. If
	 * all tracks have already been played, pick from the full set, but avoid
	 * picking the previously played track if possible. - when shuffling, PREV
	 * will go to the previously played track. Hitting PREV again will go to the
	 * track played before that, etc. When the start of the history has been
	 * reached, PREV is a no-op. When not shuffling, PREV will go to the
	 * sequentially previous track (the difference with the shuffle-case is
	 * mainly that when not shuffling, the user can back up to tracks that are
	 * not in the history).
	 * 
	 * Example: When playing an album with 10 tracks from the start, and
	 * enabling shuffle while playing track 5, the remaining tracks (6-10) will
	 * be shuffled, e.g. the final play order might be 1-2-3-4-5-8-10-6-9-7.
	 * When hitting 'prev' 8 times while playing track 7 in this example, the
	 * user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next', a
	 * random track will be picked again. If at any time user disables shuffling
	 * the next/previous track will be picked in sequential order again.
	 */

	public void prev() {
		synchronized (this) {
			if (mShuffleMode == SHUFFLE_NORMAL) {
				// go to previously-played track and remove it from the history
				int histsize = mHistory.size();
				if (histsize == 0) {
					// prev is a no-op
					return;
				}
				Integer pos = mHistory.remove(histsize - 1);
				mPlayPos = pos.intValue();
			} else {
				if (mPlayPos > 0) {
					mPlayPos--;
				} else {
					mPlayPos = mPlayListLen - 1;
				}
			}
			saveBookmarkIfNeeded();
			stop(false);
			openCurrent();
			startProgressUpdate();
			play();
			notifyChange(META_CHANGED);
		}
	}

	public void next(boolean force) {
		synchronized (this) {
			if (mPlayListLen <= 0) {
				Log.d(LOGTAG, "No play queue");
				return;
			}

			if (mShuffleMode == SHUFFLE_NORMAL) {
				// Pick random next track from the not-yet-played ones
				// TODO: make it work right after adding/removing items in the
				// queue.

				// Store the current file in the history, but keep the history
				// at a
				// reasonable size
				if (mPlayPos >= 0) {
					mHistory.add(mPlayPos);
				}
				if (mHistory.size() > MAX_HISTORY_SIZE) {
					mHistory.removeElementAt(0);
				}

				int numTracks = mPlayListLen;
				int[] tracks = new int[numTracks];
				for (int i = 0; i < numTracks; i++) {
					tracks[i] = i;
				}

				int numHistory = mHistory.size();
				int numUnplayed = numTracks;
				for (int i = 0; i < numHistory; i++) {
					int idx = mHistory.get(i).intValue();
					if (idx < numTracks && tracks[idx] >= 0) {
						numUnplayed--;
						tracks[idx] = -1;
					}
				}

				// 'numUnplayed' now indicates how many tracks have not yet
				// been played, and 'tracks' contains the indices of those
				// tracks.
				if (numUnplayed <= 0) {
					// everything's already been played
					if (mRepeatMode == REPEAT_ALL || force) {
						// pick from full set
						numUnplayed = numTracks;
						for (int i = 0; i < numTracks; i++) {
							tracks[i] = i;
						}
					} else {
						// all done
						gotoIdleState();
						if (mIsSupposedToBePlaying) {
							mIsSupposedToBePlaying = false;
							notifyChange(PLAYSTATE_CHANGED);
						}
						return;
					}
				}
				int skip = mRand.nextInt(numUnplayed);
				int cnt = -1;
				while (true) {
					while (tracks[++cnt] < 0)
						;
					skip--;
					if (skip < 0) {
						break;
					}
				}
				mPlayPos = cnt;
			} else if (mShuffleMode == SHUFFLE_AUTO) {
				doAutoShuffleUpdate();
				mPlayPos++;
			} else {
				if (mPlayPos >= mPlayListLen - 1) {
					// we're at the end of the list
					if (mRepeatMode == REPEAT_NONE && !force) {
						// all done
						gotoIdleState();
						mIsSupposedToBePlaying = false;
						notifyChange(PLAYSTATE_CHANGED);
						return;
					} else if (mRepeatMode == REPEAT_ALL || force) {
						mPlayPos = 0;
					}
				} else {
					mPlayPos++;
				}
			}
			saveBookmarkIfNeeded();
			stop(false);
			openCurrent();
			startProgressUpdate();
			play();
			notifyChange(META_CHANGED);
		}
	}

	public void cycleRepeat() {
		if (mRepeatMode == REPEAT_NONE) {
			setRepeatMode(REPEAT_ALL);
		} else if (mRepeatMode == REPEAT_ALL) {
			setRepeatMode(REPEAT_CURRENT);
			if (mShuffleMode != SHUFFLE_NONE) {
				setShuffleMode(SHUFFLE_NONE);
			}
		} else {
			setRepeatMode(REPEAT_NONE);
		}
	}

	public void toggleShuffle() {
		if (mShuffleMode == SHUFFLE_NONE) {
			setShuffleMode(SHUFFLE_NORMAL);
			if (mRepeatMode == REPEAT_CURRENT) {
				setRepeatMode(REPEAT_ALL);
			}
		} else if (mShuffleMode == SHUFFLE_NORMAL
				|| mShuffleMode == SHUFFLE_AUTO) {
			setShuffleMode(SHUFFLE_NONE);
		} else {
			Log.e("MediaPlaybackService", "Invalid shuffle mode: "
					+ mShuffleMode);
		}
	}

	private void gotoIdleState() {
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		Message msg = mDelayedStopHandler.obtainMessage();
		mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
		stopForeground(false);
		setCustomBackground();
		status.contentView.setImageViewResource(R.id.status_media_play,
				isPlaying() ? R.drawable.ic_appwidget_music_play
						: R.drawable.ic_appwidget_music_pause);
		NotificationManager mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mManager.notify(PLAYBACKSERVICE_STATUS, status);
	}

	private void saveBookmarkIfNeeded() {
		try {
			if (isPodcast()) {
				long pos = position();
				long bookmark = getBookmark();
				long duration = duration();
				if ((pos < bookmark && (pos + 10000) > bookmark)
						|| (pos > bookmark && (pos - 10000) < bookmark)) {
					// The existing bookmark is close to the current
					// position, so don't update it.
					return;
				}
				if (pos < 15000 || (pos + 10000) > duration) {
					// if we're near the start or end, clear the bookmark
					pos = 0;
				}

				// write 'pos' to the bookmark field
				ContentValues values = new ContentValues();
				values.put(MediaStore.Audio.Media.BOOKMARK, pos);
				Uri uri = ContentUris.withAppendedId(
						MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
						mCursor.getLong(IDCOLIDX));
				getContentResolver().update(uri, values, null, null);
			}
		} catch (SQLiteException ex) {
		}
	}

	// Make sure there are at least 5 items after the currently playing item
	// and no more than 10 items before.
	private void doAutoShuffleUpdate() {
		boolean notify = false;

		// remove old entries
		if (mPlayPos > 10) {
			removeTracks(0, mPlayPos - 9);
			notify = true;
		}
		// add new entries if needed
		int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
		for (int i = 0; i < to_add; i++) {
			// pick something at random from the list

			int lookback = mHistory.size();
			int idx = -1;
			while (true) {
				idx = mRand.nextInt(mAutoShuffleList.length);
				if (!wasRecentlyUsed(idx, lookback)) {
					break;
				}
				lookback /= 2;
			}
			mHistory.add(idx);
			if (mHistory.size() > MAX_HISTORY_SIZE) {
				mHistory.remove(0);
			}
			ensurePlayListCapacity(mPlayListLen + 1);
			mPlayList[mPlayListLen++] = mAutoShuffleList[idx];
			notify = true;
		}
		if (notify) {
			notifyChange(QUEUE_CHANGED);
		}
	}

	// check that the specified idx is not in the history (but only look at at
	// most lookbacksize entries in the history)
	private boolean wasRecentlyUsed(int idx, int lookbacksize) {

		// early exit to prevent infinite loops in case idx == mPlayPos
		if (lookbacksize == 0) {
			return false;
		}

		int histsize = mHistory.size();
		if (histsize < lookbacksize) {
			Log.d(LOGTAG, "lookback too big");
			lookbacksize = histsize;
		}
		int maxidx = histsize - 1;
		for (int i = 0; i < lookbacksize; i++) {
			long entry = mHistory.get(maxidx - i);
			if (entry == idx) {
				return true;
			}
		}
		return false;
	}

	// A simple variation of Random that makes sure that the
	// value it returns is not equal to the value it returned
	// previously, unless the interval is 1.
	private static class Shuffler {
		private int mPrevious;
		private Random mRandom = new Random();

		public int nextInt(int interval) {
			int ret;
			do {
				ret = mRandom.nextInt(interval);
			} while (ret == mPrevious && interval > 1);
			mPrevious = ret;
			return ret;
		}
	};

	private boolean makeAutoShuffleList() {
		ContentResolver res = getContentResolver();
		Cursor c = null;
		try {
			c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
					new String[] { MediaStore.Audio.Media._ID },
					MediaStore.Audio.Media.IS_MUSIC + "=1", null, null);
			if (c == null || c.getCount() == 0) {
				return false;
			}
			int len = c.getCount();
			long[] list = new long[len];
			for (int i = 0; i < len; i++) {
				c.moveToNext();
				list[i] = c.getLong(0);
			}
			mAutoShuffleList = list;
			return true;
		} catch (RuntimeException ex) {
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return false;
	}

	/**
	 * Removes the range of tracks specified from the play list. If a file
	 * within the range is the file currently being played, playback will move
	 * to the next file after the range.
	 * 
	 * @param first
	 *            The first file to be removed
	 * @param last
	 *            The last file to be removed
	 * @return the number of tracks deleted
	 */
	public int removeTracks(int first, int last) {
		int numremoved = removeTracksInternal(first, last);
		if (numremoved > 0) {
			notifyChange(QUEUE_CHANGED);
		}
		return numremoved;
	}

	private int removeTracksInternal(int first, int last) {
		synchronized (this) {
			if (last < first)
				return 0;
			if (first < 0)
				first = 0;
			if (last >= mPlayListLen)
				last = mPlayListLen - 1;

			boolean gotonext = false;
			if (first <= mPlayPos && mPlayPos <= last) {
				mPlayPos = first;
				gotonext = true;
			} else if (mPlayPos > last) {
				mPlayPos -= (last - first + 1);
			}
			int num = mPlayListLen - last - 1;
			for (int i = 0; i < num; i++) {
				mPlayList[first + i] = mPlayList[last + 1 + i];
			}
			mPlayListLen -= last - first + 1;

			if (gotonext) {
				if (mPlayListLen == 0) {
					stop(true);
					mPlayPos = -1;
					if (mCursor != null) {
						mCursor.close();
						mCursor = null;
					}
				} else {
					if (mPlayPos >= mPlayListLen) {
						mPlayPos = 0;
					}
					boolean wasPlaying = isPlaying();
					stop(false);
					openCurrent();
					if (wasPlaying) {
						play();
					}
				}
				notifyChange(META_CHANGED);
			}
			return last - first + 1;
		}
	}

	/**
	 * Removes all instances of the track with the given id from the playlist.
	 * 
	 * @param id
	 *            The id to be removed
	 * @return how many instances of the track were removed
	 */
	public int removeTrack(long id) {
		int numremoved = 0;
		synchronized (this) {
			for (int i = 0; i < mPlayListLen; i++) {
				if (mPlayList[i] == id) {
					numremoved += removeTracksInternal(i, i);
					i--;
				}
			}
		}
		if (numremoved > 0) {
			notifyChange(QUEUE_CHANGED);
		}
		return numremoved;
	}

	public void setShuffleMode(int shufflemode) {
		synchronized (this) {
			if (mShuffleMode == shufflemode && mPlayListLen > 0) {
				return;
			}
			mShuffleMode = shufflemode;
			notifyChange(SHUFFLEMODE_CHANGED);
			if (mShuffleMode == SHUFFLE_AUTO) {
				if (makeAutoShuffleList()) {
					mPlayListLen = 0;
					doAutoShuffleUpdate();
					mPlayPos = 0;
					openCurrent();
					play();
					notifyChange(META_CHANGED);
					return;
				} else {
					// failed to build a list of files to shuffle
					mShuffleMode = SHUFFLE_NONE;
				}
			}
			saveQueue(false);
		}
	}

	public int getShuffleMode() {
		return mShuffleMode;
	}

	public void setRepeatMode(int repeatmode) {
		synchronized (this) {
			mRepeatMode = repeatmode;
			notifyChange(REPEATMODE_CHANGED);
			saveQueue(false);
		}
	}

	public int getRepeatMode() {
		return mRepeatMode;
	}

	public int getMediaMountedCount() {
		return mMediaMountedCount;
	}

	/**
	 * Returns the path of the currently playing file, or null if no file is
	 * currently playing.
	 */
	public String getPath() {
		return mFileToPlay;
	}

	/**
	 * Returns the rowid of the currently playing file, or -1 if no file is
	 * currently playing.
	 */
	public long getAudioId() {
		synchronized (this) {
			if (mPlayPos >= 0 && mPlayer.isInitialized()) {
				return mPlayList[mPlayPos];
			}
		}
		return -1;
	}

	/**
	 * Returns the position in the queue
	 * 
	 * @return the position in the queue
	 */
	public int getQueuePosition() {
		synchronized (this) {
			return mPlayPos;
		}
	}

	/**
	 * Starts playing the track at the given position in the queue.
	 * 
	 * @param pos
	 *            The position in the queue of the track that will be played.
	 */
	public void setQueuePosition(int pos) {
		synchronized (this) {
			stop(false);
			mPlayPos = pos;
			openCurrent();
			play();
			notifyChange(META_CHANGED);
			if (mShuffleMode == SHUFFLE_AUTO) {
				doAutoShuffleUpdate();
			}
		}
	}

	public String getArtistName() {
		synchronized (this) {
			if (mCursor == null) {
				return null;
			}
			return mCursor.getString(mCursor
					.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
		}
	}

	public long getArtistId() {
		synchronized (this) {
			if (mCursor == null) {
				return -1;
			}
			return mCursor.getLong(mCursor
					.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
		}
	}

	public String getAlbumName() {
		synchronized (this) {
			if (mCursor == null) {
				return null;
			}
			return mCursor.getString(mCursor
					.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
		}
	}

	public long getAlbumId() {
		synchronized (this) {
			if (mCursor == null) {
				return -1;
			}
			return mCursor.getLong(mCursor
					.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
		}
	}

	public String getTrackName() {
		synchronized (this) {
			if (mCursor == null) {
				return null;
			}
			return mCursor.getString(mCursor
					.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
		}
	}

	private boolean isPodcast() {
		synchronized (this) {
			if (mCursor == null) {
				return false;
			}
			return (mCursor.getInt(PODCASTCOLIDX) > 0);
		}
	}

	private long getBookmark() {
		synchronized (this) {
			if (mCursor == null) {
				return 0;
			}
			return mCursor.getLong(BOOKMARKCOLIDX);
		}
	}

	/**
	 * Returns the duration of the file in milliseconds. Currently this method
	 * returns -1 for the duration of MIDI files.
	 */
	public long duration() {
		if (mPlayer.isInitialized()) {
			return mPlayer.duration();
		}
		return -1;
	}

	/**
	 * Returns the current playback position in milliseconds
	 */
	public long position() {
		if (mPlayer.isInitialized()) {
			return mPlayer.position();
		}
		return -1;
	}

	/**
	 * Seeks to the position specified.
	 * 
	 * @param pos
	 *            The position to seek to, in milliseconds
	 */
	public long seek(long pos) {
		if (mPlayer.isInitialized()) {
			if (pos < 0)
				pos = 0;
			if (pos > mPlayer.duration())
				pos = mPlayer.duration();
			return mPlayer.seek(pos);
		}
		return -1;
	}

	/**
	 * Sets the audio session ID.
	 * 
	 * @param sessionId
	 *            : the audio session ID.
	 */
	public void setAudioSessionId(int sessionId) {
		synchronized (this) {
			mPlayer.setAudioSessionId(sessionId);
		}
	}

	/**
	 * Returns the audio session ID.
	 */
	public int getAudioSessionId() {
		synchronized (this) {
			return mPlayer.getAudioSessionId();
		}
	}

	/**
	 * Provides a unified interface for dealing with midi files and other media
	 * files.
	 */
	private class MultiPlayer {
		private MediaPlayer mMediaPlayer = new MediaPlayer();
		private Handler mHandler;
		private boolean mIsInitialized = false;

		public MultiPlayer() {
			mMediaPlayer.setWakeMode(MediaPlaybackService.this,
					PowerManager.PARTIAL_WAKE_LOCK);
		}

		public void setDataSource(String path) {
			try {
				mMediaPlayer.reset();
				mMediaPlayer.setOnPreparedListener(null);
				if (path.startsWith("content://")) {
					mMediaPlayer.setDataSource(MediaPlaybackService.this,
							Uri.parse(path));
				} else {
					mMediaPlayer.setDataSource(path);
				}
				mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mMediaPlayer.prepare();
			} catch (IOException ex) {
				// TODO: notify the user why the file couldn't be opened
				mIsInitialized = false;
				return;
			} catch (IllegalArgumentException ex) {
				// TODO: notify the user why the file couldn't be opened
				mIsInitialized = false;
				return;
			}
			mMediaPlayer.setOnCompletionListener(listener);
			mMediaPlayer.setOnErrorListener(errorListener);
			Intent i = new Intent(
					AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
			i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
			i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
			sendBroadcast(i);
			mIsInitialized = true;
		}

		public boolean isInitialized() {
			return mIsInitialized;
		}

		public void start() {
			MusicUtils.debugLog(new Exception("MultiPlayer.start called"));
			mMediaPlayer.start();
		}

		public void stop() {
			mMediaPlayer.reset();
			mIsInitialized = false;
		}

		/**
		 * You CANNOT use this player anymore after calling release()
		 */
		public void release() {
			stop();
			mMediaPlayer.release();
		}

		public void pause() {
			mMediaPlayer.pause();
		}

		public void setHandler(Handler handler) {
			mHandler = handler;
		}

		MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
			public void onCompletion(MediaPlayer mp) {
				// Acquire a temporary wakelock, since when we return from
				// this callback the MediaPlayer will release its wakelock
				// and allow the device to go to sleep.
				// This temporary wakelock is released when the RELEASE_WAKELOCK
				// message is processed, but just in case, put a timeout on it.
				mWakeLock.acquire(30000);
				mHandler.sendEmptyMessage(TRACK_ENDED);
				mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
			}
		};

		MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
			public boolean onError(MediaPlayer mp, int what, int extra) {
				switch (what) {
				case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
					mIsInitialized = false;
					mMediaPlayer.release();
					// Creating a new MediaPlayer and settings its wakemode does
					// not
					// require the media service, so it's OK to do this now,
					// while the
					// service is still being restarted
					mMediaPlayer = new MediaPlayer();
					mMediaPlayer.setWakeMode(MediaPlaybackService.this,
							PowerManager.PARTIAL_WAKE_LOCK);
					mHandler.sendMessageDelayed(
							mHandler.obtainMessage(SERVER_DIED), 2000);
					return true;
				default:
					Log.d("MultiPlayer", "Error: " + what + "," + extra);
					break;
				}
				return false;
			}
		};

		public long duration() {
			return mMediaPlayer.getDuration();
		}

		public long position() {
			return mMediaPlayer.getCurrentPosition();
		}

		public long seek(long whereto) {
			mMediaPlayer.seekTo((int) whereto);
			return whereto;
		}

		public void setVolume(float vol) {
			mMediaPlayer.setVolume(vol, vol);
			mCurrentVolume = vol;
		}

		public void setAudioSessionId(int sessionId) {
			mMediaPlayer.setAudioSessionId(sessionId);
		}

		public int getAudioSessionId() {
			return mMediaPlayer.getAudioSessionId();
		}
	}

	/*
	 * By making this a static class with a WeakReference to the Service, we
	 * ensure that the Service can be GCd even when the system process still has
	 * a remote reference to the stub.
	 */
	static class ServiceStub extends IMediaPlaybackService.Stub {
		WeakReference<MediaPlaybackService> mService;

		ServiceStub(MediaPlaybackService service) {
			mService = new WeakReference<MediaPlaybackService>(service);
		}

		public void openFile(String path) {
			mService.get().open(path);
		}

		public void open(long[] list, int position) {
			mService.get().open(list, position);
		}

		public int getQueuePosition() {
			return mService.get().getQueuePosition();
		}

		public void setQueuePosition(int index) {
			mService.get().setQueuePosition(index);
		}

		public boolean isPlaying() {
			return mService.get().isPlaying();
		}

		public void stop() {
			mService.get().stop();
		}

		public void pause() {
			mService.get().pause();
		}

		public void play() {
			mService.get().play();
		}

		public void prev() {
			mService.get().prev();
		}

		public void next() {
			mService.get().next(true);
		}

		public String getTrackName() {
			return mService.get().getTrackName();
		}

		public String getAlbumName() {
			return mService.get().getAlbumName();
		}

		public long getAlbumId() {
			return mService.get().getAlbumId();
		}

		public String getArtistName() {
			return mService.get().getArtistName();
		}

		public long getArtistId() {
			return mService.get().getArtistId();
		}

		public void enqueue(long[] list, int action) {
			mService.get().enqueue(list, action);
		}

		public long[] getQueue() {
			return mService.get().getQueue();
		}

		public void moveQueueItem(int from, int to) {
			mService.get().moveQueueItem(from, to);
		}

		public String getPath() {
			return mService.get().getPath();
		}

		public long getAudioId() {
			return mService.get().getAudioId();
		}

		public long position() {
			return mService.get().position();
		}

		public long duration() {
			return mService.get().duration();
		}

		public long seek(long pos) {
			return mService.get().seek(pos);
		}

		public void setShuffleMode(int shufflemode) {
			mService.get().setShuffleMode(shufflemode);
		}

		public int getShuffleMode() {
			return mService.get().getShuffleMode();
		}

		public int removeTracks(int first, int last) {
			return mService.get().removeTracks(first, last);
		}

		public int removeTrack(long id) {
			return mService.get().removeTrack(id);
		}

		public void setRepeatMode(int repeatmode) {
			mService.get().setRepeatMode(repeatmode);
		}

		public int getRepeatMode() {
			return mService.get().getRepeatMode();
		}

		public int getMediaMountedCount() {
			return mService.get().getMediaMountedCount();
		}

		public int getAudioSessionId() {
			return mService.get().getAudioSessionId();
		}

		@Override
		public void cycleRepeat() throws RemoteException {
			// TODO Auto-generated method stub

		}

		@Override
		public void toggleShuffle() throws RemoteException {
			// TODO Auto-generated method stub

		}

		@Override
		public String getAlbumartistName() throws RemoteException {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getAlbumartistId() throws RemoteException {
			// TODO Auto-generated method stub
			return 0;
		}
	}

	private void startProgressUpdate() {
		timer.scheduleAtFixedRate(new TimerTask() {

			public void run() {
				try {
					notifyChange(PROGRESSBAR_CHANGED);
				} catch (NullPointerException e) {

				}

			}

		}, 0, 1000);
		;
	}

	private void stopProgressUpdate() {

		if (timer != null) {

			timer.cancel();
			timer = new Timer();
		}

	}

	@Override
	protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
		writer.println("" + mPlayListLen
				+ " items in queue, currently at index " + mPlayPos);
		writer.println("Currently loaded:");
		writer.println(getArtistName());
		writer.println(getAlbumName());
		writer.println(getTrackName());
		writer.println(getPath());
		writer.println("playing: " + mIsSupposedToBePlaying);
		writer.println("actual: " + mPlayer.mMediaPlayer.isPlaying());
		writer.println("shuffle mode: " + mShuffleMode);
		MusicUtils.debugDump(writer);
	}

	private final IBinder mBinder = new ServiceStub(this);

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	public void onSensorChanged(SensorEvent event) {

		SharedPreferences preferences = getSharedPreferences(
				MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
		mPreferences.getBoolean(MusicSettingsActivity.KEY_FLIP, false);

		SharedPreferences mPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);

		int flipChange = new Integer(mPrefs.getInt(
				MusicSettingsActivity.FLIP_SENSITIVITY,
				MusicSettingsActivity.DEFAULT_FLIP_SENS));

		FLIP_SENS = flipChange;

		float vals[] = event.values;
		PITCH = vals[1];// Pitch
		ROLL = vals[2];// Roll

		int nPITCH_UPER = PITCH_UPER;
		int nPITCH_LOVER = PITCH_LOVER;
		int nROLL_UPER = ROLL_UPER;
		int nROLL_LOVER = ROLL_LOVER;

		if (FLIP_SENS != 0) {
			nPITCH_UPER = PITCH_UPER - FLIP_SENS;
			nPITCH_LOVER = PITCH_LOVER + FLIP_SENS;
			nROLL_UPER = ROLL_UPER + FLIP_SENS;
			nROLL_LOVER = ROLL_LOVER - FLIP_SENS;
		}
		if (preferences.getBoolean(MusicSettingsActivity.KEY_FLIP, false)) {
			if (PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER) {
				if (ROLL < nROLL_UPER && ROLL > nROLL_LOVER) {
					if (isPlaying()) {
						pause();
						IsWorked = true;
					}
				} else if (PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER) {
					if (IsWorked) {
						if (!isPlaying()) {
							play();
							IsWorked = false;
						}
					}
				}
			}
		}
	}

	public static void setSensivity(int sensivity) {
		FLIP_SENS = sensivity - 0;

	}

	private void doPauseResume() {
		if (isPlaying()) {
			pause();
		} else {
			play();
		}
	}

	private void doNext() {

		next(true);
	}

	private void doPrev() {

		if (position() < 2000) {
			prev();
		} else {
			seek(0);
			play();
		}
	}

	@Override
	public void shakingStarted() {
		SharedPreferences preferences = getSharedPreferences(
				MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
		shake_actions_db = preferences.getString("shake_actions_db", "1");
		if (shake_actions_db.equals("1")) {
			doPauseResume();
		}
		shake_actions_db = preferences.getString("shake_actions_db", "2");
		if (shake_actions_db.equals("2")) {
			doNext();
		}
		shake_actions_db = preferences.getString("shake_actions_db", "3");
		if (shake_actions_db.equals("3")) {
			doPrev();
		}
		shake_actions_db = preferences.getString("shake_actions_db", "4");
		if (shake_actions_db.equals("4")) {
			Cursor cursor;
			cursor = MusicUtils.query(this,
					MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
					new String[] { BaseColumns._ID }, AudioColumns.IS_MUSIC
							+ "=1", null,
					MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
			if (cursor != null) {
				MusicUtils.shuffleAll(this, cursor);
				cursor.close();
			}
		}
		shake_actions_db = preferences.getString("shake_actions_db", "5");
		if (shake_actions_db.equals("5")) {
			int shuffle = getShuffleMode();
			if (shuffle == SHUFFLE_AUTO) {
				setShuffleMode(SHUFFLE_NONE);
			} else {
				setShuffleMode(SHUFFLE_AUTO);
			}
		}
	}

	@Override
	public void shakingStopped() {

	}

}