summaryrefslogtreecommitdiff
path: root/src/com/android/car/media/MediaActivity.java
blob: d6c3f8f59d921072d0069a64875fca0ea01eb5f0 (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
/*
 * Copyright (C) 2016 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.car.media;

import android.annotation.NonNull;
import android.car.Car;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.transition.Fade;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;

import com.android.car.media.common.CrossfadeImageView;
import com.android.car.media.common.MediaItemMetadata;
import com.android.car.media.common.MediaSource;
import com.android.car.media.common.MediaSourcesManager;
import com.android.car.media.common.PlaybackControls;
import com.android.car.media.common.PlaybackModel;
import com.android.car.media.drawer.MediaDrawerController;
import com.android.car.media.widgets.AppBarView;
import com.android.car.media.widgets.MetadataView;
import com.android.car.media.widgets.ViewUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import androidx.car.drawer.CarDrawerActivity;
import androidx.car.drawer.CarDrawerAdapter;

/**
 * This activity controls the UI of media. It also updates the connection status for the media app
 * by broadcast. Drawer menu is controlled by {@link MediaDrawerController}.
 */
public class MediaActivity extends CarDrawerActivity implements BrowseFragment.Callbacks,
        AppSelectionFragment.Callbacks {
    private static final String TAG = "MediaActivity";

    /** Intent extra specifying the package with the MediaBrowser */
    public static final String KEY_MEDIA_PACKAGE = "media_package";
    /** Shared preferences files */
    public static final String SHARED_PREF = "com.android.car.media";
    /** Shared preference containing the last controlled source */
    public static final String LAST_MEDIA_SOURCE_SHARED_PREF_KEY = "last_media_source";

    /** Configuration (controlled from resources) */
    private boolean mContentForwardBrowseEnabled;
    private float mBackgroundBlurRadius;
    private float mBackgroundBlurScale;
    private int mFadeDuration;

    /** Models */
    private MediaDrawerController mDrawerController;
    private MediaSource mMediaSource;
    private PlaybackModel mPlaybackModel;
    private MediaSourcesManager mMediaSourcesManager;
    private SharedPreferences mSharedPreferences;

    /** Layout views */
    private AppBarView mAppBarView;
    private CrossfadeImageView mAlbumBackground;
    private PlaybackFragment mPlaybackFragment;
    private AppSelectionFragment mAppSelectionFragment;
    private AppBarLayout mDrawerBarLayout;
    private PlaybackControls mPlaybackControls;
    private MetadataView mMetadataView;
    private ViewGroup mBrowseControlsContainer;
    private EmptyFragment mEmptyFragment;
    private ViewGroup mBrowseContainer;
    private ViewGroup mPlaybackContainer;

    /** Current state */
    private Fragment mCurrentFragment;
    private Mode mMode = Mode.BROWSING;
    private boolean mIsAppSelectorOpen;
    private MediaItemMetadata mCurrentMetadata;

    private MediaSource.Observer mMediaSourceObserver = new MediaSource.Observer() {
        @Override
        protected void onBrowseConnected(boolean success) {
            MediaActivity.this.onBrowseConnected(success);
        }

        @Override
        protected void onBrowseDisconnected() {
            MediaActivity.this.onBrowseConnected(false);
        }
    };
    private PlaybackModel.PlaybackObserver mPlaybackObserver =
            new PlaybackModel.PlaybackObserver() {
                @Override
                public void onSourceChanged() {
                    updateMetadata();
                }

                @Override
                public void onMetadataChanged() {
                    mCurrentMetadata = null;
                    updateMetadata();
                }
            };
    private MediaSource.ItemsSubscription mItemsSubscription =
            new MediaSource.ItemsSubscription() {
                @Override
                public void onChildrenLoaded(MediaSource mediaSource, String parentId,
                        List<MediaItemMetadata> items) {
                    if (mediaSource == mMediaSource) {
                        updateTabs(items);
                    } else {
                        Log.w(TAG, "Received items for a wrong source: " +
                                mediaSource.getPackageName());
                    }
                }
            };
    private AppBarView.AppBarListener mAppBarListener = new AppBarView.AppBarListener() {
        @Override
        public void onTabSelected(MediaItemMetadata item) {
            updateBrowseFragment(BrowseState.LOADED, item);
            switchToMode(Mode.BROWSING);
        }

        @Override
        public void onBack() {
            if (mCurrentFragment != null && mCurrentFragment instanceof BrowseFragment) {
                BrowseFragment fragment = (BrowseFragment) mCurrentFragment;
                fragment.navigateBack();
            }
        }

        @Override
        public void onCollapse() {
            switchToMode(Mode.BROWSING);
        }

        @Override
        public void onAppSelection() {
            if (mIsAppSelectorOpen) {
                closeAppSelector();
            } else {
                openAppSelector();
            }
        }
    };
    private MediaSourcesManager.Observer mMediaSourcesManagerObserver = () -> {
        mAppBarView.setAppSelection(!mMediaSourcesManager.getMediaSources().isEmpty());
        mAppSelectionFragment.refresh();
    };

    /**
     * Possible modes of the application UI
     */
    private enum Mode {
        /** The user is browsing a media source */
        BROWSING,
        /** The user is interacting with the full screen playback UI */
        PLAYBACK
    }

    /**
     * Possible states of the application UI
     */
    public enum BrowseState {
        /** There is no content to show */
        EMPTY,
        /** We are still in the process of obtaining data */
        LOADING,
        /** Data has been loaded */
        LOADED,
        /** The content can't be shown due an error */
        ERROR
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setMainContent(R.layout.media_activity);

        setToolbarElevation(0f);

        mContentForwardBrowseEnabled = getResources()
                .getBoolean(R.bool.forward_content_browse_enabled);
        mDrawerController = new MediaDrawerController(this, getDrawerController());
        getDrawerController().setRootAdapter(getRootAdapter());
        mAppBarView = findViewById(R.id.app_bar);
        mAppBarView.setListener(mAppBarListener);
        boolean forceBrowseTabs = getResources().getBoolean(R.bool.force_browse_tabs);
        mAppBarView.setVisibility(forceBrowseTabs ? View.VISIBLE : View.GONE);
        mPlaybackFragment = new PlaybackFragment();
        mAppSelectionFragment = new AppSelectionFragment();
        int fadeDuration = getResources().getInteger(R.integer.app_selector_fade_duration);
        mAppSelectionFragment.setEnterTransition(new Fade().setDuration(fadeDuration));
        mAppSelectionFragment.setExitTransition(new Fade().setDuration(fadeDuration));
        mPlaybackModel = new PlaybackModel(this);
        mMediaSourcesManager = new MediaSourcesManager(this);
        mDrawerBarLayout = findViewById(androidx.car.R.id.appbar);
        mDrawerBarLayout.setVisibility(forceBrowseTabs ? View.GONE : View.VISIBLE);
        mAlbumBackground = findViewById(R.id.media_background);
        mPlaybackControls = findViewById(R.id.browse_controls);
        mPlaybackControls.setModel(mPlaybackModel);
        mMetadataView = findViewById(R.id.browse_metadata);
        mMetadataView.setModel(mPlaybackModel);
        mBrowseControlsContainer = findViewById(R.id.browse_controls_container);
        mBrowseControlsContainer.setOnClickListener(view -> switchToMode(Mode.PLAYBACK));
        TypedValue outValue = new TypedValue();
        getResources().getValue(R.dimen.playback_background_blur_radius, outValue, true);
        mBackgroundBlurRadius = outValue.getFloat();
        getResources().getValue(R.dimen.playback_background_blur_scale, outValue, true);
        mBackgroundBlurScale = outValue.getFloat();
        mSharedPreferences = getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
        mFadeDuration = getResources().getInteger(
                R.integer.new_album_art_fade_in_duration);
        mEmptyFragment = new EmptyFragment();
        mBrowseContainer = findViewById(R.id.fragment_container);
        mPlaybackContainer = findViewById(R.id.playback_container);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.playback_container, mPlaybackFragment)
                .commit();
    }

    @Override
    public void onResume() {
        super.onResume();
        mPlaybackModel.registerObserver(mPlaybackObserver);
        mMediaSourcesManager.registerObserver(mMediaSourcesManagerObserver);
        handleIntent();
    }

    @Override
    public void onPause() {
        super.onPause();
        mPlaybackModel.unregisterObserver(mPlaybackObserver);
        mMediaSourcesManager.unregisterObserver(mMediaSourcesManagerObserver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mDrawerController.cleanup();
        mPlaybackControls.setModel(null);
        mMetadataView.setModel(null);
    }

    @Override
    protected CarDrawerAdapter getRootAdapter() {
        return mDrawerController == null ? null : mDrawerController.getRootAdapter();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "onNewIntent(); intent: " + (intent == null ? "<< NULL >>" : intent));
        }

        setIntent(intent);
        handleIntent();
    }

    @Override
    public void onBackPressed() {
        mPlaybackFragment.closeOverflowMenu();
        super.onBackPressed();
    }

    private void onBrowseConnected(boolean success) {
        if (!success) {
            updateTabs(null);
            mMediaSource.unsubscribeChildren(null, mItemsSubscription);
            mMediaSource.unsubscribe(mMediaSourceObserver);
            updateBrowseFragment(BrowseState.ERROR, null);
            return;
        }
        mMediaSource.subscribeChildren(null, mItemsSubscription);
    }

    private void handleIntent() {
        Intent intent = getIntent();
        String action = intent != null ? intent.getAction() : null;

        getDrawerController().closeDrawer();

        if (Car.CAR_INTENT_ACTION_MEDIA_TEMPLATE.equals(action)) {
            // The user either wants to browse a particular media source or switch to the
            // playback UI.
            String packageName = intent.getStringExtra(KEY_MEDIA_PACKAGE);
            if (packageName != null) {
                // We were told to navigate to a particular package: we open browse for it.
                closeAppSelector();
                updateBrowseSource(new MediaSource(this, packageName));
                switchToMode(Mode.BROWSING);
                return;
            }

            // If didn't receive a package name and we are playing something: show the playback
            // UI for the playing media source.
            MediaSource mediaSource = mPlaybackModel.getMediaSource();
            if (mediaSource != null) {
                closeAppSelector();
                updateBrowseSource(mPlaybackModel.getMediaSource());
                switchToMode(Mode.PLAYBACK);
                return;
            }
        }

        // In any other case, if we were already browsing something: just close drawers/overlays
        // and display what we have.
        if (mMediaSource != null) {
            closeAppSelector();
            return;
        }

        // If we don't have a current media source, we try with the last one we remember.
        MediaSource lastMediaSource = getLastMediaSource();
        if (lastMediaSource != null) {
            closeAppSelector();
            updateBrowseSource(lastMediaSource);
            switchToMode(Mode.BROWSING);
        } else {
            // If we don't have anything from before: open the app selector.
            openAppSelector();
        }
    }

    /**
     * Updates the media source being browsed. This could be necessary when the user selects
     * a different media source.
     */
    private void updateBrowseSource(MediaSource mediaSource) {
        if (Objects.equals(mediaSource, mMediaSource)) {
            // No change, nothing to do.
            return;
        }
        if (mMediaSource != null) {
            mMediaSource.unsubscribeChildren(null, mItemsSubscription);
            mMediaSource.unsubscribe(mMediaSourceObserver);
            updateTabs(new ArrayList<>());
        }
        mMediaSource = mediaSource;
        setLastMediaSource(mMediaSource);
        mAppBarView.setState(AppBarView.State.BROWSING);
        if (mMediaSource != null) {
            if (Log.isLoggable(TAG, Log.INFO)) {
                Log.i(TAG, "Browsing: " + mediaSource.getName());
            }
            ComponentName component = mMediaSource.getBrowseServiceComponentName();
            MediaManager.getInstance(this).setMediaClientComponent(component);
            // If content forward browsing is disabled, then no need to subscribe to this media
            // source.
            updateBrowseFragment(BrowseState.LOADING, null);
            if (mContentForwardBrowseEnabled) {
                Log.i(TAG, "Content forward is enabled: subscribing to " +
                        mMediaSource.getPackageName());
                mMediaSource.subscribe(mMediaSourceObserver);
            }
            mAppBarView.setAppIcon(mMediaSource.getRoundPackageIcon());
            mAppBarView.setTitle(mMediaSource.getName());
        } else {
            mAppBarView.setAppIcon(null);
            mAppBarView.setTitle(null);
        }
    }

    private boolean isCurrentMediaSourcePlaying() {
        return Objects.equals(mMediaSource, mPlaybackModel.getMediaSource());
    }

    /**
     * Updates the tabs displayed on the app bar, based on the top level items on the browse tree.
     * If there is at least one browsable item, we show the browse content of that node.
     * If there are only playable items, then we show those items.
     * If there are not items at all, we show the empty message.
     * If we receive null, we show the error message.
     *
     * @param items top level items, or null if there was an error trying load those items.
     */
    private void updateTabs(List<MediaItemMetadata> items) {
        if (items == null || items.isEmpty()) {
            mAppBarView.setItems(null);
            updateBrowseFragment(items == null ? BrowseState.ERROR : BrowseState.EMPTY, null);
            return;
        }

        items = customizeTabs(mMediaSource, items);
        List<MediaItemMetadata> browsableTopLevel = items.stream()
                .filter(item -> item.isBrowsable())
                .collect(Collectors.toList());

        if (!browsableTopLevel.isEmpty()) {
            // If we have at least a few browsable items, we show the tabs
            mAppBarView.setItems(browsableTopLevel);
            updateBrowseFragment(BrowseState.LOADED, browsableTopLevel.get(0));
        } else {
            // Otherwise, we show the top of the tree with no fabs
            mAppBarView.setItems(null);
            updateBrowseFragment(BrowseState.LOADED, null);
        }
    }

    /**
     * Extension point used to customize media items displayed on the tabs.
     *
     * @param mediaSource media source these items belong to.
     * @param items items to override.
     * @return an updated list of items.
     * @deprecated This method will be removed on b/79089344
     */
    @Deprecated
    protected List<MediaItemMetadata> customizeTabs(MediaSource mediaSource,
            List<MediaItemMetadata> items) {
        return items;
    }

    private void switchToMode(Mode mode) {
        mMode = mode;
        updateMetadata();
        switch (mode) {
            case PLAYBACK:
                ViewUtils.showViewAnimated(mPlaybackContainer, mFadeDuration);
                ViewUtils.hideViewAnimated(mBrowseContainer, mFadeDuration);
                mAppBarView.setState(AppBarView.State.PLAYING);
                break;
            case BROWSING:
                ViewUtils.hideViewAnimated(mPlaybackContainer, mFadeDuration);
                ViewUtils.showViewAnimated(mBrowseContainer, mFadeDuration);
                mAppBarView.setState(AppBarView.State.BROWSING);
                break;
        }
    }

    /**
     * Updates the browse area with either a loading state, the root node content, or the
     * content of a particular media item.
     *
     * @param state state in the process of loading browse information.
     * @param topItem if state == IDLE, this will contain the item to display,
     *                or null to display the root node.
     */
    private void updateBrowseFragment(BrowseState state, MediaItemMetadata topItem) {
        switch(state) {
            case LOADED:
                if (topItem != null) {
                    mCurrentFragment = BrowseFragment.newInstance(mMediaSource, topItem);
                    mAppBarView.setActiveItem(topItem);
                } else {
                    mCurrentFragment = BrowseFragment.newInstance(mMediaSource, null);
                    mAppBarView.setActiveItem(null);
                }
                break;
            case EMPTY:
            case LOADING:
            case ERROR:
                mCurrentFragment = mEmptyFragment;
                mEmptyFragment.setState(state, mMediaSource);
                mAppBarView.setActiveItem(null);
                break;
        }
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, mCurrentFragment)
                .commitAllowingStateLoss();
    }

    private void updateMetadata() {
        if (isCurrentMediaSourcePlaying()) {
            if (mMode == Mode.PLAYBACK) {
                ViewUtils.hideViewAnimated(mBrowseControlsContainer, mFadeDuration);
            } else {
                ViewUtils.showViewAnimated(mBrowseControlsContainer, mFadeDuration);
            }
            MediaItemMetadata metadata = mPlaybackModel.getMetadata();
            if (Objects.equals(mCurrentMetadata, metadata)) {
                return;
            }
            mCurrentMetadata = metadata;
            mUpdateAlbumArtRunnable.run();
        } else {
            mAlbumBackground.setImageBitmap(null, true);
            ViewUtils.hideViewAnimated(mBrowseControlsContainer, mFadeDuration);
        }
    }

    /**
     * We might receive new album art before we are ready to display it. If that situation happens
     * we will retrieve and render the album art when the views are already laid out.
     */
    private Runnable mUpdateAlbumArtRunnable = new Runnable() {
        @Override
        public void run() {
            MediaItemMetadata metadata = mPlaybackModel.getMetadata();
            if (metadata != null) {
                if (mAlbumBackground.getWidth() == 0 || mAlbumBackground.getHeight() == 0) {
                    // We need to wait for the view to be measured before we can render this
                    // album art.
                    mAlbumBackground.setImageBitmap(null, false);
                    mAlbumBackground.post(this);
                } else {
                    mAlbumBackground.removeCallbacks(this);
                    metadata.getAlbumArt(MediaActivity.this,
                            mAlbumBackground.getWidth(),
                            mAlbumBackground.getHeight(),
                            false)
                            .thenAccept(bitmap -> setBackgroundImage(bitmap));
                }
            } else {
                mAlbumBackground.removeCallbacks(this);
                mAlbumBackground.setImageBitmap(null, true);
            }
        }
    };

    private void setBackgroundImage(Bitmap bitmap) {
        // TODO(b/77551865): Implement image blurring once the following issue is solved:
        // b/77551557
        // bitmap = ImageUtils.blur(getContext(), bitmap, mBackgroundBlurScale,
        //        mBackgroundBlurRadius);
        mAlbumBackground.setImageBitmap(bitmap, true);
    }

    @Override
    public MediaSource getMediaSource(String packageName) {
        if (mMediaSource != null && mMediaSource.getPackageName().equals(packageName)) {
            return mMediaSource;
        }
        if (mPlaybackModel.getMediaSource() != null &&
                mPlaybackModel.getMediaSource().getPackageName().equals(packageName)) {
            return mPlaybackModel.getMediaSource();
        }
        return new MediaSource(this, packageName);
    }

    @Override
    public void onBackStackChanged() {
        // TODO: Update ActionBar
    }

    @Override
    public void onPlayableItemClicked(MediaSource mediaSource, MediaItemMetadata item) {
        mPlaybackModel.onStop();
        mediaSource.getPlaybackModel().onPlayItem(item.getId());
        setIntent(null);
        switchToMode(Mode.PLAYBACK);
    }

    private void openAppSelector() {
        mIsAppSelectorOpen = true;
        FragmentManager manager = getSupportFragmentManager();
        mAppBarView.setState(AppBarView.State.APP_SELECTION);
        manager.beginTransaction()
                .replace(R.id.app_selection_container, mAppSelectionFragment)
                .commit();
    }

    private void closeAppSelector() {
        mIsAppSelectorOpen = false;
        FragmentManager manager = getSupportFragmentManager();
        mAppBarView.setState(mMode == Mode.PLAYBACK ? AppBarView.State.PLAYING
                : AppBarView.State.BROWSING);
        manager.beginTransaction()
                .remove(mAppSelectionFragment)
                .commit();
    }

    @Override
    public List<MediaSource> getMediaSources() {
        return mMediaSourcesManager.getMediaSources()
                .stream()
                .filter(source -> source.getMediaBrowser() != null && !source.isCustom())
                .collect(Collectors.toList());
    }

    @Override
    public void onMediaSourceSelected(MediaSource mediaSource) {
        closeAppSelector();
        if (mediaSource.getMediaBrowser() != null && !mediaSource.isCustom()) {
            mCurrentMetadata = null;
            updateBrowseSource(mediaSource);
            switchToMode(Mode.BROWSING);
        } else {
            String packageName = mediaSource.getPackageName();
            Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
            startActivity(intent);
        }
    }

    private MediaSource getLastMediaSource() {
        String packageName = mSharedPreferences.getString(LAST_MEDIA_SOURCE_SHARED_PREF_KEY, null);
        if (packageName == null) {
            return null;
        }
        // Verify that the stored package name corresponds to a currently installed media source.
        for (MediaSource mediaSource : mMediaSourcesManager.getMediaSources()) {
            if (mediaSource.getPackageName().equals(packageName)) {
                return mediaSource;
            }
        }
        return null;
    }

    private void setLastMediaSource(@NonNull MediaSource mediaSource) {
        mSharedPreferences.edit()
                .putString(LAST_MEDIA_SOURCE_SHARED_PREF_KEY, mediaSource.getPackageName())
                .apply();
    }
}