Example usage for android.support.v4.media.session MediaSessionCompat FLAG_HANDLES_TRANSPORT_CONTROLS

List of usage examples for android.support.v4.media.session MediaSessionCompat FLAG_HANDLES_TRANSPORT_CONTROLS

Introduction

In this page you can find the example usage for android.support.v4.media.session MediaSessionCompat FLAG_HANDLES_TRANSPORT_CONTROLS.

Prototype

int FLAG_HANDLES_TRANSPORT_CONTROLS

To view the source code for android.support.v4.media.session MediaSessionCompat FLAG_HANDLES_TRANSPORT_CONTROLS.

Click Source Link

Document

Sets this flag on the session to indicate that it handles transport control commands through its Callback .

Usage

From source file:com.example.androidcodes.testmediaplayer.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mMusicProvider = new MusicProvider();

    // To make the app more responsive, fetch and cache catalog information now.
    // This can help improve the response time in the method
    // {@link #onLoadChildren(String, Result<List<MediaItem>>) onLoadChildren()}.
    mMusicProvider.retrieveMediaAsync(null /* Callback */);

    mPackageValidator = new PackageValidator(this);

    QueueManager queueManager = new QueueManager(mMusicProvider, getResources(),
            new QueueManager.MetadataUpdateListener() {
                @Override//from w w  w  .  j  ava 2s  .  c om
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    mSession.setMetadata(metadata);
                }

                @Override
                public void onMetadataRetrieveError() {
                    mPlaybackManager.updatePlaybackState(getString(R.string.error_no_metadata));
                }

                @Override
                public void onCurrentQueueIndexUpdated(int queueIndex) {
                    mPlaybackManager.handlePlayRequest();
                }

                @Override
                public void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue) {
                    mSession.setQueue(newQueue);
                    mSession.setQueueTitle(title);
                }
            });

    LocalPlayback playback = new LocalPlayback(this, mMusicProvider);
    mPlaybackManager = new PlaybackManager(this, getResources(), mMusicProvider, queueManager, playback);

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

    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);

    mPlaybackManager.updatePlaybackState(null);

    try {
        mMediaNotificationManager = new MediaNotificationManager(this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }

    if (!TvHelper.isTvUiMode(this)) {
        mCastSessionManager = CastContext.getSharedInstance(this).getSessionManager();
        mCastSessionManagerListener = new CastSessionManagerListener();
        mCastSessionManager.addSessionManagerListener(mCastSessionManagerListener, CastSession.class);
    }

    mMediaRouter = MediaRouter.getInstance(getApplicationContext());

    registerCarConnectionReceiver();
}

From source file:com.scooter1556.sms.android.service.MediaService.java

@RequiresApi(api = Build.VERSION_CODES.O)
@Override//from   w  w w. j  a v a 2s  .c  om
public void onCreate() {
    super.onCreate();

    Log.d(TAG, "onCreate()");

    restService = RESTService.getInstance();

    // Retrieve preferences if they exist
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Load default settings
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Initialise database
    ConnectionDatabase db = new ConnectionDatabase(this);

    // Check connection
    long id = sharedPreferences.getLong("Connection", -1);

    if (id >= 0) {
        Connection connection = db.getConnection(id);
        restService.setConnection(connection);
        isConnected = true;
    } else {
        isConnected = false;
    }

    queueManager = new QueueManager(getApplicationContext(), new QueueManager.MetadataUpdateListener() {
        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            Log.d(TAG, "onMetadataChanged()");

            mediaSession.setMetadata(metadata);
        }

        @Override
        public void onMetadataRetrieveError() {
            Log.d(TAG, "onMetadataRetrieveError()");

            playbackManager.updatePlaybackState(getString(R.string.error_no_metadata));
        }

        @Override
        public void onCurrentQueueIndexUpdated(int queueIndex) {
            Log.d(TAG, "onCurrentQueueIndexUpdated(" + queueIndex + ")");

            playbackManager.handlePlayRequest();
        }

        @Override
        public void onQueueUpdated(List<MediaSessionCompat.QueueItem> newQueue) {
            Log.d(TAG, "onQueueUpdated()");

            mediaSession.setQueue(newQueue);
            mediaSession.setQueueTitle("Now Playing");
        }
    });

    // Initialise playback manager
    playbackManager = PlaybackManager.getInstance();
    playbackManager.initialise(getApplicationContext(), this, queueManager);

    // Start a new Media Session
    mediaSession = new MediaSessionCompat(this, MediaService.class.getSimpleName());
    mediaSession.setCallback(playbackManager.getMediaSessionCallback());
    mediaSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
                    | MediaSessionCompat.FLAG_HANDLES_QUEUE_COMMANDS);

    Context context = getApplicationContext();
    Intent intent = new Intent(context, NowPlayingActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 99, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mediaSession.setSessionActivity(pendingIntent);

    mediaSessionExtras = new Bundle();
    AutoUtils.setSlotReservationFlags(mediaSessionExtras, true, true, true);
    mediaSession.setExtras(mediaSessionExtras);

    setSessionToken(mediaSession.getSessionToken());

    try {
        mediaNotificationManager = new MediaNotificationManager(this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }

    if (!TVUtils.isTvUiMode(this)) {
        castSessionManager = CastContext.getSharedInstance(this).getSessionManager();
        castSessionManagerListener = new CastSessionManagerListener();
        castSessionManager.addSessionManagerListener(castSessionManagerListener, CastSession.class);
    }

    mediaRouter = MediaRouter.getInstance(getApplicationContext());

    registerCarConnectionReceiver();

    // Register connectivity receiver
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    this.registerReceiver(connectivityChangeReceiver, intentFilter);
}

From source file:com.example.chu.googleplaylibrary.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mMusicProvider = new MusicProvider();

    // To make the app more responsive, fetch and cache catalog information now.
    // This can help improve the response time in the method
    // {@link #onLoadChildren(String, Result<List<MediaItem>>) onLoadChildren()}.
    mMusicProvider.retrieveMediaAsync(null /* Callback */);

    mPackageValidator = new PackageValidator(this);

    QueueManager queueManager = new QueueManager(mMusicProvider, getResources(),
            new QueueManager.MetadataUpdateListener() {
                @Override//  www.  j a v  a  2s .  c o  m
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    mSession.setMetadata(metadata);
                }

                @Override
                public void onMetadataRetrieveError() {
                    mPlaybackManager.updatePlaybackState(getString(R.string.error_no_metadata));
                }

                @Override
                public void onCurrentQueueIndexUpdated(int queueIndex) {
                    mPlaybackManager.handlePlayRequest();
                }

                @Override
                public void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue) {
                    mSession.setQueue(newQueue);
                    mSession.setQueueTitle(title);
                }
            });

    LocalPlayback playback = new LocalPlayback(this, mMusicProvider);
    mPlaybackManager = new PlaybackManager(this, getResources(), mMusicProvider, queueManager, playback);

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

    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);

    mPlaybackManager.updatePlaybackState(null);

    VideoCastManager.getInstance().addVideoCastConsumer(mCastConsumer);
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());

    registerCarConnectionReceiver();
}

From source file:rocks.stalin.android.app.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    timeProvider = new LocalOffsetService();
    executorService = ServiceLocator.getInstance().getService(TaskExecutor.class);
    scheduler = ServiceLocator.getInstance().getService(TaskScheduler.class);

    mMusicProvider = new MusicProvider(new ExternalStorageSource(getApplicationContext()));
    //mMusicProvider = new MusicProvider();
    // To make the app more responsive, fetch and cache catalog information now.
    // This can help improve the response time in the method
    // {@link #onLoadChildren(String, Result<List<MediaItem>>) onLoadChildren()}.
    mMusicProvider.retrieveMediaAsync(null /* Callback */);

    mPackageValidator = new PackageValidator(this);

    QueueManager queueManager = new QueueManager(mMusicProvider, getResources(),
            new QueueManager.MetadataUpdateListener() {
                @Override//  ww  w  . j ava2 s .  com
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    mSession.setMetadata(metadata);
                }

                @Override
                public void onMetadataRetrieveError() {
                    mPlaybackManager.updatePlaybackState(getString(R.string.error_no_metadata));
                }

                @Override
                public void onCurrentQueueIndexUpdated(int queueIndex) {
                    //TODO: This causes mediaPlayer the mediaplayer to get restarted twice on song change
                    //There's currently a race condition there -JJ 21/05-2017
                    //mPlaybackManager.handlePlayRequest();
                }

                @Override
                public void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue) {
                    mSession.setQueue(newQueue);
                    mSession.setQueueTitle(title);
                }
            });

    LogHelper.i(TAG, "Starting manager");

    //TODO: extract port number somewhere else, possible even not set it
    TCPServerConnectionFactory connectionFactory = new TCPServerConnectionFactory(8009, executorService);
    connectionFactory.setListener(this);
    executorService.submit(connectionFactory);

    WifiP2pManager rawManager = getSystemService(WifiP2pManager.class);
    WifiP2pManager.Channel channel = rawManager.initialize(this, getMainLooper(), null);
    WifiP2PManagerFacade manager = new WifiP2PManagerFacade(rawManager, channel);
    server = new WifiP2pServiceAnnouncer(manager, 8009, executorService);
    server.start();

    remotePlayback = new RemotePlayback(this, mMusicProvider, timeProvider, scheduler);
    mPlaybackManager = new PlaybackManager(this, getResources(), mMusicProvider, queueManager, remotePlayback);

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

    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();
    mSession.setExtras(mSessionExtras);

    mPlaybackManager.updatePlaybackState(null);

    try {
        mMediaNotificationManager = new MediaNotificationManager(this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }

    mCastSessionManager = CastContext.getSharedInstance(this).getSessionManager();
    mCastSessionManagerListener = new CastSessionManagerListener();
    mCastSessionManager.addSessionManagerListener(mCastSessionManagerListener, CastSession.class);

    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
}

From source file:com.torrenttunes.android.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

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

    mEventReceiver = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());

    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mEventReceiver);
    mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);

    // Start a new MediaSession
    mSession = new MediaSessionCompat(this, "MusicService", mEventReceiver, mMediaPendingIntent);

    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 {//  www.  ja va 2s .  c o  m
        mSession.setCallback(cb);
    }

    setSessionToken(mSession.getSessionToken());
    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);
    mSession.setExtras(mSessionExtras);

    updatePlaybackState(null);

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

    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
}

From source file:com.pi.android.brainbeats.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mMusicProvider = new MusicProvider(getApplicationContext());

    // To make the app more responsive, fetch and cache catalog information now.
    // This can help improve the response time in the method
    // {@link #onLoadChildren(String, Result<List<MediaItem>>) onLoadChildren()}.
    mMusicProvider.retrieveMediaAsync(null /* Callback */);

    mPackageValidator = new PackageValidator(this);

    QueueManager queueManager = new QueueManager(mMusicProvider, getResources(),
            new QueueManager.MetadataUpdateListener() {
                @Override//  w  w w. ja v  a2  s.  c  o m
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    mSession.setMetadata(metadata);
                }

                @Override
                public void onMetadataRetrieveError() {
                    mPlaybackManager.updatePlaybackState(getString(R.string.error_no_metadata));
                }

                @Override
                public void onCurrentQueueIndexUpdated(int queueIndex) {
                    mPlaybackManager.handlePlayRequest();
                }

                @Override
                public void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue) {
                    mSession.setQueue(newQueue);
                    mSession.setQueueTitle(title);
                }
            });

    LocalPlayback playback = new LocalPlayback(this, mMusicProvider);
    mPlaybackManager = new PlaybackManager(this, getResources(), mMusicProvider, queueManager, playback);

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

    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);

    mPlaybackManager.updatePlaybackState(null);

    try {
        mMediaNotificationManager = new MediaNotificationManager(this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }
    VideoCastManager.getInstance().addVideoCastConsumer(mCastConsumer);
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());

    registerCarConnectionReceiver();
}

From source file:com.example.android.AudioArchive.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mMusicProvider = new MusicProvider();

    // To make the app more responsive, fetch and cache catalog information now.
    // This can help improve the response time in the method
    // {@link #onLoadChildren(String, Result<List<MediaItem>>) onLoadChildren()}.
    mMusicProvider.retrieveMediaAsync(null /* Callback */);

    mPackageValidator = new PackageValidator(this);

    QueueManager queueManager = new QueueManager(mMusicProvider, getResources(),
            new QueueManager.MetadataUpdateListener() {
                @Override//from www  .  j  ava 2s.c o  m
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    mSession.setMetadata(metadata);
                }

                @Override
                public void onMetadataRetrieveError() {
                    mPlaybackManager.updatePlaybackState(getString(R.string.error_no_metadata));
                }

                @Override
                public void onCurrentQueueIndexUpdated(int queueIndex) {
                    mPlaybackManager.handlePlayRequest();
                }

                @Override
                public void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue) {
                    mSession.setQueue(newQueue);
                    mSession.setQueueTitle(title);
                }
            });

    LocalPlayback playback = new LocalPlayback(this, mMusicProvider);
    mPlaybackManager = new PlaybackManager(this, getResources(), mMusicProvider, queueManager, playback);

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

    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);

    mPlaybackManager.updatePlaybackState(null);

    try {
        mMediaNotificationManager = new MediaNotificationManager(this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }
    VideoCastManager.getInstance().addVideoCastConsumer(mCastConsumer);
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());

    registerCarConnectionReceiver();
}

From source file:com.bayapps.android.robophish.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mMusicProvider = new MusicProvider();

    // To make the app more responsive, fetch and cache catalog information now.
    // This can help improve the response time in the method
    // {@link #onLoadChildren(String, Result<List<MediaItem>>) onLoadChildren()}.
    //mMusicProvider.retrieveMediaAsync(null /* Callback */);

    mPackageValidator = new PackageValidator(this);

    QueueManager queueManager = new QueueManager(mMusicProvider, getResources(),
            new QueueManager.MetadataUpdateListener() {
                @Override//from w w  w  . j  a  v a  2s . c  o  m
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    mSession.setMetadata(metadata);
                }

                @Override
                public void onMetadataRetrieveError() {
                    mPlaybackManager.updatePlaybackState(getString(R.string.error_no_metadata));
                }

                @Override
                public void onCurrentQueueIndexUpdated(int queueIndex) {
                    mPlaybackManager.handlePlayRequest();
                }

                @Override
                public void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue) {
                    mSession.setQueue(newQueue);
                    mSession.setQueueTitle(title);
                }
            });

    LocalPlayback playback = new LocalPlayback(this, mMusicProvider);
    mPlaybackManager = new PlaybackManager(this, getResources(), mMusicProvider, queueManager, playback);

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

    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);

    mPlaybackManager.updatePlaybackState(null);

    try {
        mMediaNotificationManager = new MediaNotificationManager(this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }
    VideoCastManager.getInstance().addVideoCastConsumer(mCastConsumer);
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());

    registerCarConnectionReceiver();
}

From source file:com.example.hp.smartstor.CloudMusicManager.uamp.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mMusicProvider = new MusicProvider();

    // To make the app more responsive, fetch and cache catalog information now.
    // This can help improve the response time in the method
    // {@link #onLoadChildren(String, Result<List<MediaItem>>) onLoadChildren()}.
    mMusicProvider.retrieveMediaAsync(null /* Callback */);

    mPackageValidator = new com.example.hp.smartstor.CloudMusicManager.uamp.PackageValidator(this);

    QueueManager queueManager = new QueueManager(mMusicProvider, getResources(),
            new QueueManager.MetadataUpdateListener() {
                @Override/*ww  w  .j  a va2  s  .  c  o m*/
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    mSession.setMetadata(metadata);
                }

                @Override
                public void onMetadataRetrieveError() {
                    mPlaybackManager.updatePlaybackState(getString(R.string.error_no_metadata));
                }

                @Override
                public void onCurrentQueueIndexUpdated(int queueIndex) {
                    mPlaybackManager.handlePlayRequest();
                }

                @Override
                public void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue) {
                    mSession.setQueue(newQueue);
                    mSession.setQueueTitle(title);
                }
            });

    LocalPlayback playback = new LocalPlayback(this, mMusicProvider);
    mPlaybackManager = new PlaybackManager(this, getResources(), mMusicProvider, queueManager, playback);

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

    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);

    mPlaybackManager.updatePlaybackState(null);

    try {
        mMediaNotificationManager = new com.example.hp.smartstor.CloudMusicManager.uamp.MediaNotificationManager(
                this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }
    VideoCastManager.getInstance().addVideoCastConsumer(mCastConsumer);
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());

    registerCarConnectionReceiver();
}

From source file:org.chromium.chrome.browser.media.ui.NotificationMediaPlaybackControls.java

private void updateNotification() {
    if (mService == null)
        return;/*from ww  w .j av  a  2s .  co m*/

    if (mMediaNotificationInfo == null) {
        // Notification was hidden before we could update it.
        assert mNotificationBuilder == null;
        return;
    }

    // Android doesn't badge the icons for RemoteViews automatically when
    // running the app under the Work profile.
    if (mNotificationIcon == null) {
        Drawable notificationIconDrawable = ApiCompatibilityUtils.getUserBadgedIcon(mContext,
                R.drawable.audio_playing);
        mNotificationIcon = drawableToBitmap(notificationIconDrawable);
    }

    if (mNotificationBuilder == null) {
        mNotificationBuilder = new NotificationCompat.Builder(mContext).setSmallIcon(R.drawable.audio_playing)
                .setAutoCancel(false).setLocalOnly(true)
                .setDeleteIntent(mService.getPendingIntent(ListenerService.ACTION_STOP));
    }
    mNotificationBuilder.setOngoing(!mMediaNotificationInfo.isPaused);
    mNotificationBuilder.setContentIntent(createContentIntent());

    RemoteViews contentView = createContentView();

    contentView.setTextViewText(R.id.title, mMediaNotificationInfo.title);
    contentView.setTextViewText(R.id.status, getStatus());
    if (mNotificationIcon != null) {
        contentView.setImageViewBitmap(R.id.icon, mNotificationIcon);
    } else {
        contentView.setImageViewResource(R.id.icon, R.drawable.audio_playing);
    }

    if (mMediaNotificationInfo.isPaused) {
        contentView.setImageViewResource(R.id.playpause, R.drawable.ic_vidcontrol_play);
        contentView.setContentDescription(R.id.playpause, mPlayDescription);
        contentView.setOnClickPendingIntent(R.id.playpause,
                mService.getPendingIntent(ListenerService.ACTION_PLAY));
    } else {
        contentView.setImageViewResource(R.id.playpause, R.drawable.ic_vidcontrol_pause);
        contentView.setContentDescription(R.id.playpause, mPauseDescription);
        contentView.setOnClickPendingIntent(R.id.playpause,
                mService.getPendingIntent(ListenerService.ACTION_PAUSE));
    }

    mNotificationBuilder.setContent(contentView);
    mNotificationBuilder.setVisibility(mMediaNotificationInfo.isPrivate ? NotificationCompat.VISIBILITY_PRIVATE
            : NotificationCompat.VISIBILITY_PUBLIC);

    if (mMediaSession == null) {
        mMediaSession = new MediaSessionCompat(mContext, mContext.getString(R.string.app_name),
                new ComponentName(mContext.getPackageName(), MediaButtonReceiver.class.getName()), null);
        mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mMediaSession.setCallback(mMediaSessionCallback);
        mMediaSession.setActive(true);
    }

    mMediaSession.setMetadata(createMetadata());

    PlaybackStateCompat.Builder playbackStateBuilder = new PlaybackStateCompat.Builder()
            .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE);
    if (mMediaNotificationInfo.isPaused) {
        playbackStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED,
                PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f);
    } else {
        playbackStateBuilder.setState(PlaybackStateCompat.STATE_PLAYING,
                PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f);
    }
    mMediaSession.setPlaybackState(playbackStateBuilder.build());

    Notification notification = mNotificationBuilder.build();

    // We keep the service as a foreground service while the media is playing. When it is not,
    // the service isn't stopped but is no longer in foreground, thus at a lower priority.
    // While the service is in foreground, the associated notification can't be swipped away.
    // Moving it back to background allows the user to remove the notification.
    if (mMediaNotificationInfo.isPaused) {
        mService.stopForeground(false /* removeNotification */);

        NotificationManagerCompat manager = NotificationManagerCompat.from(mContext);
        manager.notify(R.id.media_playback_notification, notification);
    } else {
        mService.startForeground(R.id.media_playback_notification, notification);
    }
}