/*
   * (non-Javadoc)
   * @see android.app.Service#onCreate()
   */
  @Override
  public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mPlayingQueue = new ArrayList<>();
    mMusicProvider = new MusicProvider();
    mPackageValidator = new PackageValidator(this);

    // Start a new MediaSession
    mSession = new MediaSession(this, "MusicService");
    setSessionToken(mSession.getSessionToken());
    mSession.setCallback(new MediaSessionCallback());
    mSession.setFlags(
        MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);

    mPlayback = new LocalPlayback(this, mMusicProvider);
    mPlayback.setState(PlaybackState.STATE_NONE);
    mPlayback.setCallback(this);
    mPlayback.start();

    Context context = getApplicationContext();
    Intent intent = new Intent(context, NowPlayingActivity.class);
    PendingIntent pi =
        PendingIntent.getActivity(
            context, 99 /*request code*/, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mSession.setSessionActivity(pi);

    mSessionExtras = new Bundle();
    CarHelper.setSlotReservationFlags(mSessionExtras, true, true, true);
    mSession.setExtras(mSessionExtras);

    updatePlaybackState(null);

    mMediaNotificationManager = new MediaNotificationManager(this);
    mCastManager = ((UAMPApplication) getApplication()).getCastManager(getApplicationContext());

    mCastManager.addVideoCastConsumer(mCastConsumer);
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
  }
 /**
  * Helper to switch to a different Playback instance
  *
  * @param playback switch to this playback
  */
 private void switchToPlayer(Playback playback, boolean resumePlaying) {
   if (playback == null) {
     throw new IllegalArgumentException("Playback cannot be null");
   }
   // suspend the current one.
   int oldState = mPlayback.getState();
   int pos = mPlayback.getCurrentStreamPosition();
   String currentMediaId = mPlayback.getCurrentMediaId();
   LogHelper.d(TAG, "Current position from " + playback + " is ", pos);
   mPlayback.stop(false);
   playback.setCallback(this);
   playback.setCurrentStreamPosition(pos < 0 ? 0 : pos);
   playback.setCurrentMediaId(currentMediaId);
   playback.start();
   // finally swap the instance
   mPlayback = playback;
   switch (oldState) {
     case PlaybackState.STATE_BUFFERING:
     case PlaybackState.STATE_CONNECTING:
     case PlaybackState.STATE_PAUSED:
       mPlayback.pause();
       break;
     case PlaybackState.STATE_PLAYING:
       if (resumePlaying && QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
         mPlayback.play(mPlayingQueue.get(mCurrentIndexOnQueue));
       } else if (!resumePlaying) {
         mPlayback.pause();
       } else {
         mPlayback.stop(true);
       }
       break;
     case PlaybackState.STATE_NONE:
       break;
     default:
       LogHelper.d(TAG, "Default called. Old state is ", oldState);
   }
 }
  /*
   * (non-Javadoc)
   * @see android.app.Service#onCreate()
   */
  @Override
  public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mPlayingQueue = new ArrayList<>();
    mMusicProvider = new MusicProvider();
    mPackageValidator = new PackageValidator(this);

    ComponentName mediaButtonReceiver = new ComponentName(this, RemoteControlReceiver.class);

    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mediaButtonReceiver);
    PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);

    // Start a new MediaSessionCompat
    mSession =
        new MediaSessionCompat(this, "MusicService", mediaButtonReceiver, mediaPendingIntent);

    /*
    final MediaSessionCallback cb = new MediaSessionCallback();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Shouldn't really have to do this but the MediaSessionCompat method uses
        // an internal proxy class, which doesn't forward events such as
        // onPlayFromMediaId when running on Lollipop.
        final MediaSession session = (MediaSession) mSession.getMediaSession();
        session.setCallback(new MediaSessionCallbackProxy(cb));
    } else {
        mSession.setCallback(cb);
    }
    */

    setSessionToken(mSession.getSessionToken());
    mSession.setCallback(new MediaSessionCallback());
    mSession.setFlags(
        MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
            | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);

    mPlayback = new LocalPlayback(this, mMusicProvider);
    mPlayback.setState(PlaybackStateCompat.STATE_NONE);
    mPlayback.setCallback(this);
    mPlayback.start();

    Context context = getApplicationContext();
    Intent intent = new Intent(context, NowPlayingActivity.class);
    PendingIntent pi =
        PendingIntent.getActivity(
            context, 99 /*request code*/, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mSession.setSessionActivity(pi);

    mSessionExtras = new Bundle();
    CarHelper.setSlotReservationFlags(mSessionExtras, true, true, true);
    WearHelper.setSlotReservationFlags(mSessionExtras, true, true);
    WearHelper.setUseBackgroundFromTheme(mSessionExtras, true);
    mSession.setExtras(mSessionExtras);

    updatePlaybackState(null);

    mMediaNotificationManager = new MediaNotificationManager(this);
    mCastManager = VideoCastManager.getInstance();
    mCastManager.addVideoCastConsumer(mCastConsumer);
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());

    IntentFilter filter = new IntentFilter(CarHelper.ACTION_MEDIA_STATUS);
    mCarConnectionReceiver =
        new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            String connectionEvent = intent.getStringExtra(CarHelper.MEDIA_CONNECTION_STATUS);
            mIsConnectedToCar = CarHelper.MEDIA_CONNECTED.equals(connectionEvent);
            LogHelper.i(
                TAG,
                "Connection event to Android Auto: ",
                connectionEvent,
                " isConnectedToCar=",
                mIsConnectedToCar);
          }
        };
    registerReceiver(mCarConnectionReceiver, filter);
  }