summaryrefslogtreecommitdiffstats
path: root/samples/Support7Demos/src/com/example/android/supportv7/media/SessionManager.java
blob: 1c00192de09bb1165ed6744c4721eab3262fb87b (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
/*
 * Copyright (C) 2013 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.example.android.supportv7.media;

import android.app.PendingIntent;
import android.net.Uri;
import android.support.v7.media.MediaItemStatus;
import android.support.v7.media.MediaSessionStatus;
import android.util.Log;

import java.util.List;
import java.util.ArrayList;

/**
 * SessionManager manages a media session as a queue. It supports common
 * queuing behaviors such as enqueue/remove of media items, pause/resume/stop,
 * etc.
 *
 * Actual playback of a single media item is abstracted into a Player interface,
 * and is handled outside this class.
 */
public class SessionManager implements Player.Callback {
    private static final String TAG = "SessionManager";
    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);

    private String mName;
    private int mSessionId;
    private int mItemId;
    private boolean mPaused;
    private boolean mSessionValid;
    private Player mPlayer;
    private Callback mCallback;
    private List<PlaylistItem> mPlaylist = new ArrayList<PlaylistItem>();

    public SessionManager(String name) {
        mName = name;
    }

    public boolean isPaused() {
        return hasSession() && mPaused;
    }

    public boolean hasSession() {
        return mSessionValid;
    }

    public String getSessionId() {
        return mSessionValid ? Integer.toString(mSessionId) : null;
    }

    public PlaylistItem getCurrentItem() {
        return mPlaylist.isEmpty() ? null : mPlaylist.get(0);
    }

    // Returns the cached playlist (note this is not responsible for updating it)
    public List<PlaylistItem> getPlaylist() {
        return mPlaylist;
    }

    // Updates the playlist asynchronously, calls onPlaylistReady() when finished.
    public void updateStatus() {
        if (DEBUG) {
            log("updateStatus");
        }
        checkPlayer();
        // update the statistics first, so that the stats string is valid when
        // onPlaylistReady() gets called in the end
        mPlayer.updateTrackInfo();

        if (mPlaylist.isEmpty()) {
            // If queue is empty, don't forget to call onPlaylistReady()!
            onPlaylistReady();
        } else if (mPlayer.isQueuingSupported()) {
            // If player supports queuing, get status of each item. Player is
            // responsible to call onPlaylistReady() after last getStatus().
            // (update=1 requires player to callback onPlaylistReady())
            for (int i = 0; i < mPlaylist.size(); i++) {
                PlaylistItem item = mPlaylist.get(i);
                mPlayer.getStatus(item, (i == mPlaylist.size() - 1) /* update */);
            }
        } else {
            // Otherwise, only need to get status for current item. Player is
            // responsible to call onPlaylistReady() when finished.
            mPlayer.getStatus(getCurrentItem(), true /* update */);
        }
    }

    public PlaylistItem add(Uri uri, String mime) {
        return add(uri, mime, null);
    }

    public PlaylistItem add(Uri uri, String mime, PendingIntent receiver) {
        if (DEBUG) {
            log("add: uri=" + uri + ", receiver=" + receiver);
        }
        // create new session if needed
        startSession();
        checkPlayerAndSession();

        // append new item with initial status PLAYBACK_STATE_PENDING
        PlaylistItem item = new PlaylistItem(
                Integer.toString(mSessionId), Integer.toString(mItemId), uri, mime, receiver);
        mPlaylist.add(item);
        mItemId++;

        // if player supports queuing, enqueue the item now
        if (mPlayer.isQueuingSupported()) {
            mPlayer.enqueue(item);
        }
        updatePlaybackState();
        return item;
    }

    public PlaylistItem remove(String iid) {
        if (DEBUG) {
            log("remove: iid=" + iid);
        }
        checkPlayerAndSession();
        return removeItem(iid, MediaItemStatus.PLAYBACK_STATE_CANCELED);
    }

    public PlaylistItem seek(String iid, long pos) {
        if (DEBUG) {
            log("seek: iid=" + iid +", pos=" + pos);
        }
        checkPlayerAndSession();
        // seeking on pending items are not yet supported
        checkItemCurrent(iid);

        PlaylistItem item = getCurrentItem();
        if (pos != item.getPosition()) {
            item.setPosition(pos);
            if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PLAYING
                    || item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED) {
                mPlayer.seek(item);
            }
        }
        return item;
    }

    public PlaylistItem getStatus(String iid) {
        checkPlayerAndSession();

        // This should only be called for local player. Remote player is
        // asynchronous, need to use updateStatus() instead.
        if (mPlayer.isRemotePlayback()) {
            throw new IllegalStateException(
                    "getStatus should not be called on remote player!");
        }

        for (PlaylistItem item : mPlaylist) {
            if (item.getItemId().equals(iid)) {
                if (item == getCurrentItem()) {
                    mPlayer.getStatus(item, false);
                }
                return item;
            }
        }
        return null;
    }

    public void pause() {
        if (DEBUG) {
            log("pause");
        }
        if (!mSessionValid) {
            return;
        }
        checkPlayer();
        mPaused = true;
        updatePlaybackState();
    }

    public void resume() {
        if (DEBUG) {
            log("resume");
        }
        if (!mSessionValid) {
            return;
        }
        checkPlayer();
        mPaused = false;
        updatePlaybackState();
    }

    public void stop() {
        if (DEBUG) {
            log("stop");
        }
        if (!mSessionValid) {
            return;
        }
        checkPlayer();
        mPlayer.stop();
        mPlaylist.clear();
        mPaused = false;
        updateStatus();
    }

    public String startSession() {
        if (!mSessionValid) {
            mSessionId++;
            mItemId = 0;
            mPaused = false;
            mSessionValid = true;
            return Integer.toString(mSessionId);
        }
        return null;
    }

    public boolean endSession() {
        if (mSessionValid) {
            mSessionValid = false;
            return true;
        }
        return false;
    }

    MediaSessionStatus getSessionStatus(String sid) {
        int sessionState = (sid != null && sid.equals(mSessionId)) ?
                MediaSessionStatus.SESSION_STATE_ACTIVE :
                    MediaSessionStatus.SESSION_STATE_INVALIDATED;

        return new MediaSessionStatus.Builder(sessionState)
                .setQueuePaused(mPaused)
                .build();
    }

    // Suspend the playback manager. Put the current item back into PENDING
    // state, and remember the current playback position. Called when switching
    // to a different player (route).
    public void suspend(long pos) {
        for (PlaylistItem item : mPlaylist) {
            item.setRemoteItemId(null);
            item.setDuration(0);
        }
        PlaylistItem item = getCurrentItem();
        if (DEBUG) {
            log("suspend: item=" + item + ", pos=" + pos);
        }
        if (item != null) {
            if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PLAYING
                    || item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED) {
                item.setState(MediaItemStatus.PLAYBACK_STATE_PENDING);
                item.setPosition(pos);
            }
        }
    }

    // Unsuspend the playback manager. Restart playback on new player (route).
    // This will resume playback of current item. Furthermore, if the new player
    // supports queuing, playlist will be re-established on the remote player.
    public void unsuspend() {
        if (DEBUG) {
            log("unsuspend");
        }
        if (mPlayer.isQueuingSupported()) {
            for (PlaylistItem item : mPlaylist) {
                mPlayer.enqueue(item);
            }
        }
        updatePlaybackState();
    }

    // Player.Callback
    @Override
    public void onError() {
        finishItem(true);
    }

    @Override
    public void onCompletion() {
        finishItem(false);
    }

    @Override
    public void onPlaylistChanged() {
        // Playlist has changed, update the cached playlist
        updateStatus();
    }

    @Override
    public void onPlaylistReady() {
        // Notify activity to update Ui
        if (mCallback != null) {
            mCallback.onStatusChanged();
        }
    }

    private void log(String message) {
        Log.d(TAG, mName + ": " + message);
    }

    private void checkPlayer() {
        if (mPlayer == null) {
            throw new IllegalStateException("Player not set!");
        }
    }

    private void checkSession() {
        if (!mSessionValid) {
            throw new IllegalStateException("Session not set!");
        }
    }

    private void checkPlayerAndSession() {
        checkPlayer();
        checkSession();
    }

    private void checkItemCurrent(String iid) {
        PlaylistItem item = getCurrentItem();
        if (item == null || !item.getItemId().equals(iid)) {
            throw new IllegalArgumentException("Item is not current!");
        }
    }

    private void updatePlaybackState() {
        PlaylistItem item = getCurrentItem();
        if (item != null) {
            if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PENDING) {
                item.setState(mPaused ? MediaItemStatus.PLAYBACK_STATE_PAUSED
                        : MediaItemStatus.PLAYBACK_STATE_PLAYING);
                if (!mPlayer.isQueuingSupported()) {
                    mPlayer.play(item);
                }
            } else if (mPaused && item.getState() == MediaItemStatus.PLAYBACK_STATE_PLAYING) {
                mPlayer.pause();
                item.setState(MediaItemStatus.PLAYBACK_STATE_PAUSED);
            } else if (!mPaused && item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED) {
                mPlayer.resume();
                item.setState(MediaItemStatus.PLAYBACK_STATE_PLAYING);
            }
            // notify client that item playback status has changed
            if (mCallback != null) {
                mCallback.onItemChanged(item);
            }
        }
        updateStatus();
    }

    private PlaylistItem removeItem(String iid, int state) {
        checkPlayerAndSession();
        List<PlaylistItem> queue =
                new ArrayList<PlaylistItem>(mPlaylist.size());
        PlaylistItem found = null;
        for (PlaylistItem item : mPlaylist) {
            if (iid.equals(item.getItemId())) {
                if (mPlayer.isQueuingSupported()) {
                    mPlayer.remove(item.getRemoteItemId());
                } else if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PLAYING
                        || item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED){
                    mPlayer.stop();
                }
                item.setState(state);
                found = item;
                // notify client that item is now removed
                if (mCallback != null) {
                    mCallback.onItemChanged(found);
                }
            } else {
                queue.add(item);
            }
        }
        if (found != null) {
            mPlaylist = queue;
            updatePlaybackState();
        } else {
            log("item not found");
        }
        return found;
    }

    private void finishItem(boolean error) {
        PlaylistItem item = getCurrentItem();
        if (item != null) {
            removeItem(item.getItemId(), error ?
                    MediaItemStatus.PLAYBACK_STATE_ERROR :
                        MediaItemStatus.PLAYBACK_STATE_FINISHED);
            updateStatus();
        }
    }

    // set the Player that this playback manager will interact with
    public void setPlayer(Player player) {
        mPlayer = player;
        checkPlayer();
        mPlayer.setCallback(this);
    }

    // provide a callback interface to tell the UI when significant state changes occur
    public void setCallback(Callback callback) {
        mCallback = callback;
    }

    @Override
    public String toString() {
        String result = "Media Queue: ";
        if (!mPlaylist.isEmpty()) {
            for (PlaylistItem item : mPlaylist) {
                result += "\n" + item.toString();
            }
        } else {
            result += "<empty>";
        }
        return result;
    }

    public interface Callback {
        void onStatusChanged();
        void onItemChanged(PlaylistItem item);
    }
}