Example usage for android.support.v4.media.session MediaControllerCompat MediaControllerCompat

List of usage examples for android.support.v4.media.session MediaControllerCompat MediaControllerCompat

Introduction

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

Prototype

public MediaControllerCompat(Context context, Token token) throws RemoteException 

Source Link

Usage

From source file:com.example.chu.googleplaylibrary.ui.BaseActivity.java

private void connectToSession(MediaSessionCompat.Token token) throws RemoteException {
    MediaControllerCompat mediaController = new MediaControllerCompat(this, token);
    setSupportMediaController(mediaController);

}

From source file:net.simno.klingar.playback.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    Timber.d("onCreate");
    KlingarApp.get(this).component().inject(this);

    Playback playback = new LocalPlayback(getApplicationContext(), musicController, audioManager, wifiManager);
    playbackManager = new PlaybackManager(queueManager, this, AndroidClock.DEFAULT, playback);

    session = new MediaSessionCompat(this, "MusicService");

    try {// ww  w . jav  a 2  s.  co  m
        MediaControllerCompat mediaController = new MediaControllerCompat(this.getApplicationContext(),
                session.getSessionToken());
        musicController.setMediaController(mediaController);
    } catch (RemoteException e) {
        Timber.e(e, "Could not create MediaController");
        throw new IllegalStateException();
    }

    session.setCallback(playbackManager.getMediaSessionCallback());
    session.setFlags(FLAG_HANDLES_MEDIA_BUTTONS | FLAG_HANDLES_TRANSPORT_CONTROLS);

    Context context = getApplicationContext();
    Intent intent = new Intent(context, KlingarActivity.class);
    session.setSessionActivity(PendingIntent.getActivity(context, 99, intent, FLAG_UPDATE_CURRENT));

    playbackManager.updatePlaybackState();

    mediaNotificationManager = new MediaNotificationManager(this, musicController, queueManager, rx);

    castSessionManager = CastContext.getSharedInstance(this).getSessionManager();
    castSessionManagerListener = new CastSessionManagerListener();
    castSessionManager.addSessionManagerListener(castSessionManagerListener, CastSession.class);

    mediaRouter = MediaRouter.getInstance(getApplicationContext());

    timelineManager = new TimelineManager(musicController, queueManager, media, rx);
    timelineManager.start();
}

From source file:android.support.mediacompat.client.ClientBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();/*  ww  w .j a v  a  2 s  .com*/
    MediaControllerCompat controller;
    try {
        controller = new MediaControllerCompat(context,
                (MediaSessionCompat.Token) extras.getParcelable(KEY_SESSION_TOKEN));
    } catch (RemoteException ex) {
        // Do nothing.
        return;
    }
    int method = extras.getInt(KEY_METHOD_ID, 0);

    if (ACTION_CALL_MEDIA_CONTROLLER_METHOD.equals(intent.getAction()) && extras != null) {
        Bundle arguments;
        switch (method) {
        case SEND_COMMAND:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controller.sendCommand(arguments.getString("command"), arguments.getBundle("extras"),
                    new ResultReceiver(null));
            break;
        case ADD_QUEUE_ITEM:
            controller.addQueueItem((MediaDescriptionCompat) extras.getParcelable(KEY_ARGUMENT));
            break;
        case ADD_QUEUE_ITEM_WITH_INDEX:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controller.addQueueItem((MediaDescriptionCompat) arguments.getParcelable("description"),
                    arguments.getInt("index"));
            break;
        case REMOVE_QUEUE_ITEM:
            controller.removeQueueItem((MediaDescriptionCompat) extras.getParcelable(KEY_ARGUMENT));
            break;
        case SET_VOLUME_TO:
            controller.setVolumeTo(extras.getInt(KEY_ARGUMENT), 0);
            break;
        case ADJUST_VOLUME:
            controller.adjustVolume(extras.getInt(KEY_ARGUMENT), 0);
            break;
        }
    } else if (ACTION_CALL_TRANSPORT_CONTROLS_METHOD.equals(intent.getAction()) && extras != null) {
        TransportControls controls = controller.getTransportControls();
        Bundle arguments;
        switch (method) {
        case PLAY:
            controls.play();
            break;
        case PAUSE:
            controls.pause();
            break;
        case STOP:
            controls.stop();
            break;
        case FAST_FORWARD:
            controls.fastForward();
            break;
        case REWIND:
            controls.rewind();
            break;
        case SKIP_TO_PREVIOUS:
            controls.skipToPrevious();
            break;
        case SKIP_TO_NEXT:
            controls.skipToNext();
            break;
        case SEEK_TO:
            controls.seekTo(extras.getLong(KEY_ARGUMENT));
            break;
        case SET_RATING:
            controls.setRating((RatingCompat) extras.getParcelable(KEY_ARGUMENT));
            break;
        case PLAY_FROM_MEDIA_ID:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controls.playFromMediaId(arguments.getString("mediaId"), arguments.getBundle("extras"));
            break;
        case PLAY_FROM_SEARCH:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controls.playFromSearch(arguments.getString("query"), arguments.getBundle("extras"));
            break;
        case PLAY_FROM_URI:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controls.playFromUri((Uri) arguments.getParcelable("uri"), arguments.getBundle("extras"));
            break;
        case SEND_CUSTOM_ACTION:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controls.sendCustomAction(arguments.getString("action"), arguments.getBundle("extras"));
            break;
        case SEND_CUSTOM_ACTION_PARCELABLE:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controls.sendCustomAction((PlaybackStateCompat.CustomAction) arguments.getParcelable("action"),
                    arguments.getBundle("extras"));
            break;
        case SKIP_TO_QUEUE_ITEM:
            controls.skipToQueueItem(extras.getLong(KEY_ARGUMENT));
            break;
        case PREPARE:
            controls.prepare();
            break;
        case PREPARE_FROM_MEDIA_ID:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controls.prepareFromMediaId(arguments.getString("mediaId"), arguments.getBundle("extras"));
            break;
        case PREPARE_FROM_SEARCH:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controls.prepareFromSearch(arguments.getString("query"), arguments.getBundle("extras"));
            break;
        case PREPARE_FROM_URI:
            arguments = extras.getBundle(KEY_ARGUMENT);
            controls.prepareFromUri((Uri) arguments.getParcelable("uri"), arguments.getBundle("extras"));
            break;
        case SET_CAPTIONING_ENABLED:
            controls.setCaptioningEnabled(extras.getBoolean(KEY_ARGUMENT));
            break;
        case SET_REPEAT_MODE:
            controls.setRepeatMode(extras.getInt(KEY_ARGUMENT));
            break;
        case SET_SHUFFLE_MODE:
            controls.setShuffleMode(extras.getInt(KEY_ARGUMENT));
            break;
        }
    }
}

From source file:com.somexapps.wyre.services.MediaService.java

private void initMediaSessions() {
    // Initialize player
    mediaPlayer = new MediaPlayer();

    // Add listener to handle completion of song
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override/*from  w ww .  jav a2s.co m*/
        public void onCompletion(MediaPlayer mp) {
            // Send intent to play next song in MediaService list
            Intent nextSong = new Intent(getApplicationContext(), MediaService.class);
            nextSong.setAction(ACTION_NEXT);
            startService(nextSong);
        }
    });

    // Set up session and controller
    // Create the media session
    mediaSession = new MediaSessionCompat(this, MEDIA_SESSION_TAG, mediaSessionComponentName, null);

    // Set up controller
    try {
        mediaController = new MediaControllerCompat(getApplicationContext(), mediaSession.getSessionToken());
    } catch (RemoteException e) {
        Log.e(TAG, "Unable to set up media controller: " + e.getMessage());
    }

    // Set up callbacks for media session
    mediaSession.setCallback(new MediaSessionCompat.Callback() {
        @Override
        public void onPlay() {
            super.onPlay();
            Log.d(TAG, "Playing media");
            buildNotification(generateAction(R.drawable.ic_pause_white_36dp,
                    getString(R.string.media_service_notification_pause), ACTION_PAUSE));
        }

        @Override
        public void onPause() {
            super.onPause();
            Log.d(TAG, "Pausing media");
            buildNotification(generateAction(R.drawable.ic_play_arrow_white_36dp,
                    getString(R.string.media_service_notification_play), ACTION_PLAY));
        }

        @Override
        public void onSkipToNext() {
            super.onSkipToNext();
            Log.d(TAG, "Skipping to next song");

            // Update the notification with the next song info
            buildNotification(generateAction(R.drawable.ic_pause_white_36dp,
                    getString(R.string.media_service_notification_pause), ACTION_PAUSE));
        }

        @Override
        public void onSkipToPrevious() {
            super.onSkipToPrevious();
            Log.d(TAG, "Skipping to previous song");

            // Update the notification with the previous song info
            buildNotification(generateAction(R.drawable.ic_pause_white_36dp,
                    getString(R.string.media_service_notification_pause), ACTION_PAUSE));
        }

        @Override
        public void onFastForward() {
            super.onFastForward();
        }

        @Override
        public void onRewind() {
            super.onRewind();
        }

        @Override
        public void onStop() {
            super.onStop();
        }

        @Override
        public void onSeekTo(long pos) {
            super.onSeekTo(pos);
        }

        @Override
        public void onSetRating(RatingCompat rating) {
            super.onSetRating(rating);
        }
    });
}

From source file:com.scooter1556.sms.android.activity.BaseActivity.java

private void connectToSession(MediaSessionCompat.Token token) throws RemoteException {
    MediaControllerCompat mediaController = new MediaControllerCompat(this, token);
    MediaControllerCompat.setMediaController(this, mediaController);
    mediaController.registerCallback(mediaControllerCallback);

    if (shouldShowControls()) {
        showPlaybackControls();// w  w  w .  j  av  a2 s  .  com
    } else {
        hidePlaybackControls();
    }

    if (controlsFragment != null) {
        controlsFragment.onConnected();
    }

    onMediaControllerConnected();
}

From source file:com.mylovemhz.simplay.MediaControlFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    if (savedInstanceState != null) {
        token = savedInstanceState.getParcelable(STATE_TOKEN);
        previousDrawable = savedInstanceState.getInt(STATE_PREVIOUS);
        pauseDrawableResource = savedInstanceState.getInt(STATE_PAUSE);
        playDrawableResource = savedInstanceState.getInt(STATE_PLAY);
        nextDrawable = savedInstanceState.getInt(STATE_NEXT);
    }/*from w ww  .ja  v  a 2 s.co m*/

    albumImage = (ImageView) view.findViewById(R.id.albumImage);
    artistText = (TextView) view.findViewById(R.id.artistText);
    nextButton = (ImageButton) view.findViewById(R.id.nextButton);
    playPauseButton = (ImageButton) view.findViewById(R.id.playPauseButton);
    previousButton = (ImageButton) view.findViewById(R.id.previousButton);
    seekBar = (SeekBar) view.findViewById(R.id.seekBar);
    titleText = (TextView) view.findViewById(R.id.titleText);
    try {
        mediaController = new MediaControllerCompat(getContext(), token);
        mediaController.registerCallback(mediaControllerCallback);
    } catch (RemoteException e) {
        Log.e(TAG, e.getMessage());
    }

    initViews();
}

From source file:com.torrenttunes.android.ui.BaseActivity.java

private void connectToSession(MediaSessionCompat.Token token) {

    try {/*from   w ww  . j a v  a2  s.c om*/

        LogUtils.LOGD(TAG, "Session Token: " + token);
        mMediaController = new MediaControllerCompat(this, token);

        mMediaController.registerCallback(mMediaControllerCallback);

        if (shouldShowControls()) {
            showPlaybackControls();
        } else {
            LogHelper.d(TAG, "connectionCallback.onConnected: " + "hiding controls because metadata is null");
            hidePlaybackControls();
        }

        if (mControlsFragment != null) {
            mControlsFragment.onConnected();
        }

        onMediaControllerConnected();

    } catch (RemoteException ex) {

    }
}

From source file:nuclei.media.MediaInterface.java

void onConnected() {
    try {//from  w ww  .  jav a 2s . co  m
        Context context = mFragmentActivity == null ? mLActivity : mFragmentActivity;
        if (context == null)
            return;
        mMediaControls = new MediaControllerCompat(context, mMediaBrowser.getSessionToken());
        mMediaCallback = new MediaControllerCompat.Callback() {
            @Override
            public void onPlaybackStateChanged(PlaybackStateCompat state) {
                MediaInterface.this.onPlaybackStateChanged(state);
            }

            @Override
            public void onSessionEvent(String event, Bundle extras) {
                MediaInterface.this.onSessionEvent(event, extras);
            }

            @Override
            public void onMetadataChanged(MediaMetadataCompat metadata) {
                MediaInterface.this.onMetadataChanged(metadata);
            }
        };
        mMediaControls.registerCallback(mMediaCallback);

        if (mFragmentActivity != null) {
            MediaControllerCompat.setMediaController(mFragmentActivity, mMediaControls);
            //mFragmentActivity.setSupportMediaController(mMediaControls);
        } else if (mLActivity != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            setMediaControllerL();

        if (mPlayerControls != null)
            mPlayerControls.setMediaControls(mCallbacks, mMediaControls);

        if (mMediaControls.getPlaybackState() != null)
            onPlaybackStateChanged(mMediaControls.getPlaybackState());

        final Intent intent = mFragmentActivity == null ? mLActivity.getIntent()
                : mFragmentActivity.getIntent();
        if (MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH.equals(intent.getAction())) {
            final Bundle params = intent.getExtras();
            final String query = params.getString(SearchManager.QUERY);
            LOG.i("Starting from voice search query=" + query);
            mMediaControls.getTransportControls().playFromSearch(query, params);
        }
        if (mCallbacks != null) {
            mCallbacks.onConnected(this);
            MediaMetadataCompat metadataCompat = mMediaControls.getMetadata();
            if (metadataCompat != null) {
                final long duration = metadataCompat.getLong(MediaMetadataCompat.METADATA_KEY_DURATION);
                if (duration > 0)
                    mCallbacks.setTimeTotal(this, duration);
            }
        }

        Bundle extras = mMediaControls.getExtras();
        if (extras != null && extras.containsKey(MediaService.EXTRA_CONNECTED_CAST)) {
            mCallbacks.onCasting(this, extras.getString(MediaService.EXTRA_CONNECTED_CAST));
        }

        if (mPlayerControls != null && mPlayerControls.isPlaying())
            mHandler.start();

        if (mSurface != null)
            setSurface(mSurface);

        LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ACTION_CONNECTED));
    } catch (RemoteException err) {
        LOG.e("Error in onConnected", err);
    }
}

From source file:com.appdevper.mediaplayer.activity.BaseActivity.java

private void connectToSession(MediaSessionCompat.Token token) throws RemoteException {
    MediaControllerCompat mediaController = new MediaControllerCompat(this, token);
    setSupportMediaController(mediaController);
    mediaController.registerCallback(mMediaControllerCallback);

    if (shouldShowControls()) {
        showPlaybackControls();/*w ww. j  a va  2  s . c  o m*/
    } else {
        LogHelper.d(TAG, "connectionCallback.onConnected: " + "hiding controls because metadata is null");
        hidePlaybackControls();
    }

    if (mControlsFragment != null) {
        mControlsFragment.onConnected();
    }

    onMediaControllerConnected();
}

From source file:com.teocci.utubinbg.BackgroundAudioService.java

/**
 * Initializes media sessions and receives media events
 */// w w  w  .jav a  2  s . c o  m
private void initMediaSessions() {
    // Make sure the media player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    //
    // Remember that to use this, we have to declare the android.permission.WAKE_LOCK
    // permission in AndroidManifest.xml.
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

    ComponentName eventReceiver = new ComponentName(getApplicationContext().getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    PendingIntent buttonReceiverIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(Intent.ACTION_MEDIA_BUTTON), PendingIntent.FLAG_UPDATE_CURRENT);

    mSession = new MediaSessionCompat(getApplicationContext(), "simple player session", eventReceiver,
            buttonReceiverIntent);

    try {
        mController = new MediaControllerCompat(getApplicationContext(), mSession.getSessionToken());

        mSession.setCallback(new MediaSessionCompat.Callback() {
            @Override
            public void onPlay() {
                super.onPlay();
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onPause() {

                super.onPause();
                pauseVideo();
                buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY));
            }

            @Override
            public void onSkipToNext() {
                super.onSkipToNext();
                if (!isStarting) {
                    playNext();
                }
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onSkipToPrevious() {
                super.onSkipToPrevious();
                if (!isStarting) {
                    playPrevious();
                }
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onStop() {
                super.onStop();
                stopPlayer();
                //remove notification and stop service
                NotificationManager notificationManager = (NotificationManager) getApplicationContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(1);
                Intent intent = new Intent(getApplicationContext(), BackgroundAudioService.class);
                stopService(intent);
            }

            @Override
            public void onSetRating(RatingCompat rating) {
                super.onSetRating(rating);
            }
        });
    } catch (RemoteException re) {
        re.printStackTrace();
    }
}