-
Notifications
You must be signed in to change notification settings - Fork 20
/
MusicPlaybackService.java
2694 lines (2415 loc) · 83.2 KB
/
MusicPlaybackService.java
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
/*
* Copyright (C) 2012 Andrew Neal
* Copyright (C) 2014 OpenSilk Productions LLC
*
* 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.andrew.apollo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.audiofx.AudioEffect;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import com.andrew.apollo.provider.MusicProvider;
import com.andrew.apollo.provider.MusicProviderUtil;
import com.andrew.apollo.provider.MusicStore;
import com.andrew.apollo.utils.Lists;
import com.andrew.apollo.utils.MusicUtils;
import org.opensilk.cast.callbacks.IMediaCastConsumer;
import org.opensilk.cast.exceptions.NoConnectionException;
import org.opensilk.cast.exceptions.TransientNetworkDisconnectionException;
import org.opensilk.cast.helpers.CastServiceConnectionCallback;
import org.opensilk.cast.helpers.LocalCastServiceManager;
import org.opensilk.cast.manager.MediaCastManager;
import org.opensilk.cast.util.CastPreferences;
import org.opensilk.music.BuildConfig;
import org.opensilk.music.api.meta.ArtInfo;
import org.opensilk.music.api.model.Song;
import org.opensilk.music.artwork.ArtworkProviderUtil;
import org.opensilk.music.ServiceBroadcastReceiver;
import org.opensilk.music.cast.CastWebServer;
import org.opensilk.music.util.CursorHelpers;
import org.opensilk.music.util.Projections;
import org.opensilk.music.R;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Scheduler;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import timber.log.Timber;
/**
* A backbround {@link Service} used to keep music playing between activities
* and when the user moves Apollo into the background.
*/
public class MusicPlaybackService extends Service {
private static final String TAG = "MusicPlaybackService";
private static final boolean D = BuildConfig.DEBUG;
public static final String APOLLO_PACKAGE_NAME = BuildConfig.APPLICATION_ID;
/**
* Indicates that the music has paused or resumed
*/
public static final String PLAYSTATE_CHANGED = APOLLO_PACKAGE_NAME+".playstatechanged";
/**
* Indicates that music playback position within
* a title was changed
*/
public static final String POSITION_CHANGED = APOLLO_PACKAGE_NAME+".positionchanged";
/**
* Indicates the meta data has changed in some way, like a track change
*/
public static final String META_CHANGED = APOLLO_PACKAGE_NAME+".metachanged";
/**
* Indicates the queue has been updated
*/
public static final String QUEUE_CHANGED = APOLLO_PACKAGE_NAME+".queuechanged";
/**
* Indicates the repeat mode chaned
*/
public static final String REPEATMODE_CHANGED = APOLLO_PACKAGE_NAME+".repeatmodechanged";
/**
* Indicates the shuffle mode chaned
*/
public static final String SHUFFLEMODE_CHANGED = APOLLO_PACKAGE_NAME+".shufflemodechanged";
/**
* For backwards compatibility reasons, also provide sticky
* broadcasts under the music package
*/
public static final String MUSIC_PACKAGE_NAME = "com.android.music";
/**
* Called to indicate a general service commmand. Used in
* {@link MediaButtonIntentReceiver}
*/
public static final String SERVICECMD = APOLLO_PACKAGE_NAME+".musicservicecommand";
public static final String EXTERNAL_SERVICECMD = MUSIC_PACKAGE_NAME+".musicservicecommand";
/**
* Called to go toggle between pausing and playing the music
*/
public static final String TOGGLEPAUSE_ACTION = APOLLO_PACKAGE_NAME+".togglepause";
/**
* Called to go to pause the playback
*/
public static final String PAUSE_ACTION = APOLLO_PACKAGE_NAME+".pause";
/**
* Called to go to stop the playback
*/
public static final String STOP_ACTION = APOLLO_PACKAGE_NAME+".stop";
/**
* Called to go to the previous track
*/
public static final String PREVIOUS_ACTION = APOLLO_PACKAGE_NAME+".previous";
/**
* Called to go to the next track
*/
public static final String NEXT_ACTION = APOLLO_PACKAGE_NAME+".next";
/**
* Called to change the repeat mode
*/
public static final String REPEAT_ACTION = APOLLO_PACKAGE_NAME+".repeat";
/**
* Called to change the shuffle mode
*/
public static final String SHUFFLE_ACTION = APOLLO_PACKAGE_NAME+".shuffle";
/**
* Called to update the service about the foreground state of Apollo's activities
*/
public static final String FOREGROUND_STATE_CHANGED = APOLLO_PACKAGE_NAME+".fgstatechanged";
public static final String NOW_IN_FOREGROUND = "nowinforeground";
public static final String FROM_MEDIA_BUTTON = "frommediabutton";
/**
* Used to easily notify a list that it should refresh. i.e. A playlist
* changes
*/
public static final String REFRESH = APOLLO_PACKAGE_NAME+".refresh";
/**
* Used by the alarm intent to shutdown the service after being idle
*/
private static final String SHUTDOWN = APOLLO_PACKAGE_NAME+".shutdown";
/**
* Called to update the remote control client
*/
public static final String UPDATE_LOCKSCREEN = APOLLO_PACKAGE_NAME+".updatelockscreen";
public static final String CMDNAME = "command";
public static final String CMDTOGGLEPAUSE = "togglepause";
public static final String CMDSTOP = "stop";
public static final String CMDPAUSE = "pause";
public static final String CMDPLAY = "play";
public static final String CMDPREVIOUS = "previous";
public static final String CMDNEXT = "next";
public static final String CMDNOTIF = "buttonId";
private static final int IDCOLIDX = 0;
/**
* Moves a list to the front of the queue
*/
public static final int NOW = 1;
/**
* Moves a list to the next position in the queue
*/
public static final int NEXT = 2;
/**
* Moves a list to the last position in the queue
*/
public static final int LAST = 3;
/**
* Shuffles no songs, turns shuffling off
*/
public static final int SHUFFLE_NONE = 0;
/**
* Shuffles all songs
*/
public static final int SHUFFLE_NORMAL = 1;
/**
* Party shuffle
*/
public static final int SHUFFLE_AUTO = 2;
/**
* Turns repeat off
*/
public static final int REPEAT_NONE = 0;
/**
* Repeats the current track in a list
*/
public static final int REPEAT_CURRENT = 1;
/**
* Repeats all the tracks in a list
*/
public static final int REPEAT_ALL = 2;
/**
* Idle time before stopping the foreground notfication (1 minute)
*/
private static final int IDLE_DELAY = 60000 * 6;
/**
* Song play time used as threshold for rewinding to the beginning of the
* track instead of skipping to the previous track when getting the PREVIOUS
* command
*/
private static final long REWIND_INSTEAD_PREVIOUS_THRESHOLD = 3000;
/**
* The max size allowed for the track history
*/
static final int MAX_HISTORY_SIZE = 100;
/**
* Keeps a mapping of the track history
*/
private final LinkedList<Integer> mHistory = Lists.newLinkedList();
private final LinkedList<Integer> mAutoHistory = Lists.newLinkedList();
/**
* Used to shuffle the tracks
*/
private final Shuffler mShuffler = new Shuffler();
/**
* Used to save the queue as 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
*/
private static final char HEX_DIGITS[] = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
/**
* Service stub
*/
private final IBinder mBinder;
/**
* The media player
*/
private LocalMusicPlayer mPlayer;
/**
* the cast media player
*/
private CastMusicPlayer mCastPlayer;
/**
* Keeps the service running when the screen is off
*/
private WakeLock mWakeLock;
/**
* Alarm intent for removing the notification when nothing is playing
* for some time
*/
private AlarmManager mAlarmManager;
private PendingIntent mShutdownIntent;
private boolean mShutdownScheduled;
/**
* The cursor used to retrieve info on the current track and run the
* necessary queries to play audio files
*/
private Cursor mCursor;
/**
* Monitors the audio state
*/
private AudioManager mAudioManager;
/**
* Settings used to save and retrieve the queue and history
*/
private SharedPreferences mPreferences;
/**
* Used to know when the service is active
*/
private int mConnectedClients = 0;
/**
* Used to know if something should be playing or not
*/
private boolean mIsSupposedToBePlaying = false;
/**
* Used to indicate if the queue can be saved
*/
private boolean mQueueIsSaveable = true;
/**
* Used to track what type of audio focus loss caused the playback to pause
*/
private boolean mPausedByTransientLossOfFocus = false;
/**
* Used to track whether any of Apollo's activities is in the foreground
*/
private boolean mAnyActivityInForeground = false;
// We use this to distinguish between different cards when saving/restoring
// playlists
private int mCardId;
private int mPlayListLen = 0;
private int mPlayPos = -1;
private int mNextPlayPos = -1;
private long mLastKnowPosition = 0;
private int mOpenFailedCounter = 0;
private int mMediaMountedCount = 0;
private int mShuffleMode = SHUFFLE_NONE;
private int mRepeatMode = REPEAT_NONE;
private long[] mPlayList = null;
private long[] mAutoShuffleList = null;
private MusicPlayerHandler mPlayerHandler;
private BroadcastReceiver mUnmountReceiver = null;
/**
* Used to build the notification
*/
private NotificationHelper mNotificationHelper;
/**
* handles mediasession on L and Remotecontrolclient on older apis
*/
private MediaSessionHelper mMediaSessionHelper;
/**
* Proxy for artwork provider
*/
private ArtworkProviderUtil mArtworkUtil;
/**
*
*/
private boolean isCastingEnabled;
/**
* Token for SilkCastService
*/
private LocalCastServiceManager.ServiceToken mCastServiceToken;
/**
* Cast manager
*/
private MediaCastManager mCastManager;
/**
* Cast manager callbacks
*/
private IMediaCastConsumer mCastConsumer;
/**
* Http server for service cast devices
*/
private CastWebServer mCastServer;
/**
* indicates whether we are doing a local or a remote playback
*/
public static enum PlaybackLocation {
LOCAL,
REMOTE
}
/**
* Current playback location
*/
private PlaybackLocation mPlaybackLocation = PlaybackLocation.LOCAL;
/**
* Fetches remote progress while we are in background
*/
private Subscription mRemoteProgressSubscription;
/**
* Worker used to process intents
*/
Scheduler.Worker mHandleIntentWorker;
MediaButtonHandler mMediaButtonHandler;
public MusicPlaybackService() {
super();
mBinder = new ApolloServiceBinder(this);
}
@Override
public IBinder onBind(final Intent intent) {
if (D) Log.d(TAG, "Service bound, intent = " + intent);
cancelShutdown();
mConnectedClients++;
return mBinder;
}
@Override
public boolean onUnbind(final Intent intent) {
if (D) Log.d(TAG, "Service unbound");
mConnectedClients--;
saveQueue(true);
if (mIsSupposedToBePlaying || 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.
} else if (mPlayListLen > 0 || mPlayerHandler.hasMessages(MusicPlayerHandler.TRACK_ENDED)) {
scheduleDelayedShutdown();
return true;
}
stopSelf();
return true;
}
@Override
public void onRebind(final Intent intent) {
cancelShutdown();
mConnectedClients++;
}
@Override
public void onCreate() {
if (D) Log.d(TAG, "Creating service");
super.onCreate();
// Initialize the notification helper
mNotificationHelper = new NotificationHelper(this);
// Create artwork cache
mArtworkUtil = new ArtworkProviderUtil(this);
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt the UI.
final HandlerThread thread = new HandlerThread("MusicPlayerHandler",
android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Initialize the handler
mPlayerHandler = new MusicPlayerHandler(this, thread.getLooper());
mHandleIntentWorker = Schedulers.newThread().createWorker();
// Initialize the audio manager and register any headset controls for
// playback
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mMediaSessionHelper = new MediaSessionHelper(this);
mMediaSessionHelper.setup();
// Initialize the preferences
mPreferences = getSharedPreferences("Service", 0);
mCardId = getCardId();
registerExternalStorageListener();
// Initialize the media player
mPlayer = new LocalMusicPlayer(this);
mPlayer.setHandler(mPlayerHandler);
isCastingEnabled = CastPreferences.getBoolean(this, CastPreferences.KEY_CAST_ENABLED, true);
if (isCastingEnabled) {
// Bind to the cast service
mCastServiceToken = LocalCastServiceManager.bindToService(this, mCastServiceConnectionCallback);
}
mMediaButtonHandler = new MediaButtonHandler(this);
// Initialize the intent filter and each action
final IntentFilter filter = new IntentFilter();
filter.addAction(SERVICECMD);
filter.addAction(EXTERNAL_SERVICECMD);
filter.addAction(TOGGLEPAUSE_ACTION);
filter.addAction(PAUSE_ACTION);
filter.addAction(STOP_ACTION);
filter.addAction(NEXT_ACTION);
filter.addAction(PREVIOUS_ACTION);
filter.addAction(REPEAT_ACTION);
filter.addAction(SHUFFLE_ACTION);
// Attach the broadcast listener
registerReceiver(mIntentReceiver, filter);
// Initialize the wake lock
final PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
mWakeLock.setReferenceCounted(false);
// Initialize the delayed shutdown intent
final Intent shutdownIntent = new Intent(this, MusicPlaybackService.class);
shutdownIntent.setAction(SHUTDOWN);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);
// Listen for the idle state
scheduleDelayedShutdown();
// Bring the queue back
reloadQueue();
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
@Override
public void onDestroy() {
if (D) Log.d(TAG, "Destroying service");
mConnectedClients = 0;
// Remove any sound effects
final Intent audioEffectsIntent = new Intent(
AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION);
audioEffectsIntent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
audioEffectsIntent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(audioEffectsIntent);
// remove any pending alarms
mAlarmManager.cancel(mShutdownIntent);
// Release the player
mPlayer.release();
mPlayer = null;
// Remove the audio focus listener and lock screen controls
mAudioManager.abandonAudioFocus(mAudioFocusListener);
mMediaSessionHelper.teardown();
// Remove any callbacks from the handler
mPlayerHandler.removeCallbacksAndMessages(null);
// Kill player thread
mPlayerHandler.getLooper().quit();
//release the worker
mHandleIntentWorker.unsubscribe();
mMediaButtonHandler.removeCallbacksAndMessages(null);
// Close the cursor
closeCursor();
// Unregister the mount listener
unregisterReceiver(mIntentReceiver);
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver);
mUnmountReceiver = null;
}
// Unregister with cast manager
if (mCastManager != null) {
// kill the remote app.
try {
mCastManager.stopApplication();
} catch (Exception ignored) { /*pass*/ }
mCastManager.removeCastConsumer(mCastConsumer);
mCastManager = null;
}
if (mRemoteProgressSubscription != null) {
mRemoteProgressSubscription.unsubscribe();
mRemoteProgressSubscription = null;
}
if (mCastPlayer != null) {
mCastPlayer.release();
mCastPlayer = null;
}
if (mCastServiceToken != null) {
// Unbind cast service
LocalCastServiceManager.unbindFromService(mCastServiceToken);
}
// Stop http server
stopCastServer();
// Release the wake lock
releaseWakeLock();
super.onDestroy();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level >= TRIM_MEMORY_COMPLETE) {
mArtworkUtil.trim();
}
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
if (D) Log.d(TAG, "Got new intent " + intent + ", startId = " + startId);
if (intent != null) {
final String action = intent.getAction();
if (intent.hasExtra(NOW_IN_FOREGROUND)) {
mAnyActivityInForeground = intent.getBooleanExtra(NOW_IN_FOREGROUND, false);
updateNotification();
// look and see if we were just disconnected
// mCastManager.reconnectSessionIfPossible(this, false, 2);
new Handler().post(new Runnable() {
@Override
public void run() {
updateCastManagerUiCounter(mAnyActivityInForeground);
}
});
}
if (SHUTDOWN.equals(action)) {
mShutdownScheduled = false;
releaseServiceUiAndStop();
return START_NOT_STICKY;
}
if (Intent.ACTION_MEDIA_BUTTON.equals(action)) {
mMediaButtonHandler.processIntent(intent);
} else {
postCommandIntent(intent);
}
}
// Make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
scheduleDelayedShutdown();
if (intent != null && intent.getBooleanExtra(FROM_MEDIA_BUTTON, false)) {
MediaButtonIntentReceiver.completeWakefulIntent(intent);
}
return START_STICKY;
}
private void updateCastManagerUiCounter(final boolean visible) {
if (!isCastingEnabled) {
return;
}
if (mCastManager != null) {
if (visible) {
mCastManager.incrementUiCounter();
if (mRemoteProgressSubscription != null) {
mRemoteProgressSubscription.unsubscribe();
mRemoteProgressSubscription =null;
}
} else {
mCastManager.decrementUiCounter();
if (mRemoteProgressSubscription == null
|| mRemoteProgressSubscription.isUnsubscribed()) {
mRemoteProgressSubscription = createRemoteProgressHandler();
}
}
} else {
// if we haven't bound to the cast service yet we will wait a little and try again.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
updateCastManagerUiCounter(visible);
}
}, 100);
}
}
private void releaseServiceUiAndStop() {
if (isPlaying()
|| mPausedByTransientLossOfFocus
|| mPlayerHandler.hasMessages(MusicPlayerHandler.TRACK_ENDED)) {
return;
}
if (D) Log.d(TAG, "Nothing is playing anymore, releasing notification");
mNotificationHelper.killNotification();
mAudioManager.abandonAudioFocus(mAudioFocusListener);
if (mRemoteProgressSubscription != null) {
mRemoteProgressSubscription.unsubscribe();
mRemoteProgressSubscription = null;
}
if (mConnectedClients <= 0) {
saveQueue(true);
stopSelf();
}
}
void postCommandIntent(final Intent intent) {
mHandleIntentWorker.schedule(new Action0() {
@Override
public void call() {
handleCommandIntent(intent);
}
});
}
private void handleCommandIntent(Intent intent) {
final String action = intent.getAction();
final String command = (SERVICECMD.equals(action) || EXTERNAL_SERVICECMD.equals(action))
? intent.getStringExtra(CMDNAME) : null;
if (D) Log.d(TAG, "handleCommandIntent: action = " + action + ", command = " + command);
if (CMDNEXT.equals(command) || NEXT_ACTION.equals(action)) {
gotoNext(true);
} else if (CMDPREVIOUS.equals(command) || PREVIOUS_ACTION.equals(action)) {
if (position() < REWIND_INSTEAD_PREVIOUS_THRESHOLD) {
prev();
} else {
seekAndPlay(0);
}
} else if (CMDTOGGLEPAUSE.equals(command) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
setPausedByTransientLossOfFocus(false);
} else {
play();
}
} else if (CMDPAUSE.equals(command) || PAUSE_ACTION.equals(action)) {
pause();
setPausedByTransientLossOfFocus(false);
} else if (CMDPLAY.equals(command)) {
play();
} else if (CMDSTOP.equals(command) || STOP_ACTION.equals(action)) {
pause();
seek(0);
setPausedByTransientLossOfFocus(false);
releaseServiceUiAndStop();
} else if (REPEAT_ACTION.equals(action)) {
cycleRepeat();
} else if (SHUFFLE_ACTION.equals(action)) {
cycleShuffle();
}
}
/**
* Updates the notification, considering the current play and activity state
*/
private void updateNotification() {
if (!mAnyActivityInForeground && isPlaying()) {
mNotificationHelper.buildNotification(getAlbumName(), getArtistName(),
getTrackName(), getAlbumArtThumbnail(), isPlaying(), mMediaSessionHelper.getSessionToken());
} else if (mAnyActivityInForeground) {
mNotificationHelper.killNotification();
}
}
/**
* releases wakelock
*/
void releaseWakeLock() {
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
}
/**
* acquires wakelock
*/
void acquireWakeLock() {
mWakeLock.acquire();
}
void acquireWakeLock(long milli) {
mWakeLock.acquire(milli);
}
/**
* Set if received message with AUDIOFOCUS_LOSS_TRANSIENT
* @param yes
*/
void setPausedByTransientLossOfFocus(boolean yes) {
synchronized (this) {
mPausedByTransientLossOfFocus = yes;
}
}
/**
* Used by handler to determine if playback should resume after focus lost
* @return
*/
boolean isPausedByTransientLossOfFocus() {
return mPausedByTransientLossOfFocus;
}
/**
* Fetches the current player
* @return
*/
IMusicPlayer getPlayer() {
if (isRemotePlayback()) {
if (mCastPlayer != null) {
return mCastPlayer;
} else {
Timber.e("Wanted remote playback but cast player is null!");
setPlaybackLocation(PlaybackLocation.LOCAL);
}
}
return mPlayer;
}
void switchToCastPlayer() {
Timber.d("switchToCastPlayer");
startCastServer();
if (mPlayer.isInitialized()) {
mLastKnowPosition = mPlayer.position();
}
if (isRemotePlayback()) {
setPlaybackLocation(PlaybackLocation.LOCAL);
}
stop(false);
setPlaybackLocation(PlaybackLocation.REMOTE);
openCurrentAndNext();
if (mLastKnowPosition > 0) {
seekAndPlay(mLastKnowPosition);
} else {
play();
}
}
void switchToLocalPlayer() {
Timber.d("switchToLocalPlayer");
if (getPlayer() == mPlayer) {
Timber.w("Current player is local player");
return;
}
if (mCastPlayer != null && mCastPlayer.isInitialized() && mCastPlayer.isConnected()) {
mLastKnowPosition = mCastPlayer.position();
}
if (!isRemotePlayback()) {
setPlaybackLocation(PlaybackLocation.REMOTE);
}
stop(false);
setPlaybackLocation(PlaybackLocation.LOCAL);
openCurrentAndNext();
if (mLastKnowPosition > 0) {
seek(mLastKnowPosition);
}
stopCastServer();
}
void setPlaybackLocation(PlaybackLocation location) {
mPlaybackLocation = location;
}
PlaybackLocation getPlaybackLocation() {
return mPlaybackLocation;
}
void setSupposedToBePlaying(boolean playing) {
mIsSupposedToBePlaying = playing;
}
boolean isSupposedToBePlaying() {
return mIsSupposedToBePlaying;
}
void recoverFromTransientDisconnect() {
updatePlaybackLocation(PlaybackLocation.REMOTE);
if (mCastServer == null) {
startCastServer();
}
if (mCastManager.isConnected()) {
try {
if (mCastManager.isRemoteMediaLoaded() && mCastManager.isRemoteMediaPlaying()) {
Log.d(TAG, "onConnectivityRecovered: remote media currently playing");
position();// force update the local position
if (mRemoteProgressSubscription == null
|| mRemoteProgressSubscription.isUnsubscribed()) {
// restart progress updater if needed
mRemoteProgressSubscription = createRemoteProgressHandler();
}
} else {
switchToCastPlayer();
}
} catch (TransientNetworkDisconnectionException e) {
Log.w(TAG, "onConnectivityRecovered(1) TransientNetworkDisconnection");
} catch (NoConnectionException e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "onConnectivityRecoverd: Whoa, we arent connected??");
}
}
/**
* @return A card ID used to save and restore playlists, i.e., the queue.
*/
private int getCardId() {
final ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(Uri.parse("content://media/external/fs_id"), null, null,
null, null);
int mCardId = -1;
if (cursor != null && cursor.moveToFirst()) {
mCardId = cursor.getInt(0);
cursor.close();
cursor = null;
}
return mCardId;
}
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath The path to mount point for the removed media
*/
public void closeExternalStorageFiles(final String storagePath) {
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.
*/