android.support.v4.media.session.MediaSessionCompat Java Examples

The following examples show how to use android.support.v4.media.session.MediaSessionCompat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RemoteControlClientLP.java    From Popeens-DSub with GNU General Public License v3.0 7 votes vote down vote up
@Override
public void updatePlaylist(List<DownloadFile> playlist) {
	List<MediaSessionCompat.QueueItem> queue = new ArrayList<>();

	for(DownloadFile file: playlist) {
		Entry entry = file.getSong();
		Bundle extras = new Bundle();
		extras.putLong(MediaMetadataCompat.METADATA_KEY_DURATION,
				((entry.getDuration() == null) ? 0 : (entry.getDuration() * 1000)));

		MediaDescriptionCompat description = new MediaDescriptionCompat.Builder()
				.setMediaId(entry.getId())
				.setTitle(entry.getTitle())
				.setSubtitle(entry.getArtist())
				.setDescription(entry.getAlbum())
				.setExtras(extras)
				.build();
		MediaSessionCompat.QueueItem item = new MediaSessionCompat.QueueItem(description, entry.getId().hashCode());
		queue.add(item);
	}

	mediaSession.setQueue(queue);
	currentQueue = playlist;
}
 
Example #2
Source File: QueueHelper.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
/**
 * Create a random queue.
 *
 * @param musicProvider the provider used for fetching music.
 * @return list containing {@link MediaSessionCompat.QueueItem}'s
 */
public static List<MediaSessionCompat.QueueItem> getRandomQueue(MusicProvider musicProvider) {
    List<MediaMetadataCompat> result = new ArrayList<>();

    for (String genre : musicProvider.getGenres()) {
        Iterable<MediaMetadataCompat> tracks = musicProvider.getMusicsByGenre(genre);
        for (MediaMetadataCompat track : tracks) {
            if (ThreadLocalRandom.current().nextBoolean()) {
                result.add(track);
            }
        }
    }
    LogUtils.d(TAG, "getRandomQueue: result.size=", result.size());

    Collections.shuffle(result);

    return convertToQueue(result, MEDIA_ID_MUSICS_BY_SEARCH, "random");
}
 
Example #3
Source File: StreamFragment.java    From Twire with GNU General Public License v3.0 6 votes vote down vote up
private void initializePlayer() {
    if (player == null) {
        player = new SimpleExoPlayer.Builder(getContext()).build();
        player.addListener(this);
        mVideoView.setPlayer(player);
        mVideoView.setPlaybackPreparer(this);

        if (currentMediaSource != null)
            player.prepare(currentMediaSource);

        mediaSession = new MediaSessionCompat(getContext(), getContext().getPackageName());
        MediaSessionConnector mediaSessionConnector = new MediaSessionConnector(mediaSession);
        mediaSessionConnector.setPlayer(player);
        mediaSession.setActive(true);

        progressHandler.postDelayed(progressRunnable, 1000);
    }
}
 
Example #4
Source File: QueueHelper.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
private static List<MediaSessionCompat.QueueItem> convertToQueue(
        Iterable<MediaMetadataCompat> tracks, String... categories) {
    List<MediaSessionCompat.QueueItem> queue = new ArrayList<>();
    int count = 0;
    for (MediaMetadataCompat track : tracks) {

        // We create a hierarchy-aware mediaID, so we know what the queue is about by looking
        // at the QueueItem media IDs.
        String hierarchyAwareMediaID = MediaIDHelper.createMediaID(
                track.getDescription().getMediaId(), categories);

        MediaMetadataCompat trackCopy = new MediaMetadataCompat.Builder(track)
                .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, hierarchyAwareMediaID)
                .build();

        // We don't expect queues to change after created, so we use the item index as the
        // queueId. Any other number unique in the queue would work.
        MediaSessionCompat.QueueItem item = new MediaSessionCompat.QueueItem(trackCopy.getDescription(), count++);
        queue.add(item);
    }
    return queue;

}
 
Example #5
Source File: ServicePlayerController.java    From Jockey with Apache License 2.0 6 votes vote down vote up
private void fetchMediaSessionToken() {
    if (mBinding == null) {
        return;
    }

    if (!mMediaSessionToken.hasValue() || mMediaSessionToken.getValue() == null) {
        MediaSessionCompat.Token token = null;

        try {
            token = mBinding.getMediaSessionToken();
        } catch (RemoteException e) {
            Timber.e(e, "Failed to get session token");
        }

        if (token != null) {
            mMediaSessionToken.onNext(token);
        }
    }
}
 
Example #6
Source File: ReadAloudService.java    From a with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 初始化MediaSession
 */
private void initMediaSession() {
    ComponentName mComponent = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mComponent);
    PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(this, 0,
            mediaButtonIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    mediaSessionCompat = new MediaSessionCompat(this, TAG, mComponent, mediaButtonReceiverPendingIntent);
    mediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
            return MediaButtonIntentReceiver.handleIntent(ReadAloudService.this, mediaButtonEvent);
        }
    });
    mediaSessionCompat.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
}
 
Example #7
Source File: MediaNotificationManager.java    From carstream-android-auto with Apache License 2.0 6 votes vote down vote up
public MediaNotificationManager(Context context, MediaSessionCompat.Token sessionToken) throws RemoteException {
    mContext = context;
    mSessionToken = sessionToken;
    updateSessionToken();

    mNotificationManager = NotificationManagerCompat.from(context);

    String pkg = context.getPackageName();
    mPauseIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mPlayIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mPreviousIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mNextIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mStopIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_STOP).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mStopCastIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_STOP_CASTING).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);

    // Cancel all notifications to handle the case where the Service was killed and
    // restarted by the system.
    mNotificationManager.cancelAll();
}
 
Example #8
Source File: CumulusBrowseService.java    From CumulusTV with MIT License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    mSession = new MediaSessionCompat(this, "session tag");
    setSessionToken(mSession.getSessionToken());
    mSession.setCallback(new CustomMediaSession(getApplicationContext(), new CustomMediaSession.Callback() {
        @Override
        public void onPlaybackStarted(JsonChannel channel) {
            showNotification(channel);
        }

        @Override
        public void onPlaybackEnded() {
            stopForeground(true);
            removeNotification();
        }
    }));
    mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
        MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
}
 
Example #9
Source File: MediaNotificationManager.java    From delion with Apache License 2.0 6 votes vote down vote up
private MediaSessionCompat createMediaSession() {
    MediaSessionCompat mediaSession = new MediaSessionCompat(
            mContext,
            mContext.getString(R.string.app_name),
            new ComponentName(mContext.getPackageName(),
                    getButtonReceiverClassName()),
            null);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
            | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(mMediaSessionCallback);

    // TODO(mlamouri): the following code is to work around a bug that hopefully
    // MediaSessionCompat will handle directly. see b/24051980.
    try {
        mediaSession.setActive(true);
    } catch (NullPointerException e) {
        // Some versions of KitKat do not support AudioManager.registerMediaButtonIntent
        // with a PendingIntent. They will throw a NullPointerException, in which case
        // they should be able to activate a MediaSessionCompat with only transport
        // controls.
        mediaSession.setActive(false);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mediaSession.setActive(true);
    }
    return mediaSession;
}
 
Example #10
Source File: FullScreenPlayerActivity.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
private void connectToSession(MediaSessionCompat.Token token) {
    try {
        mMediaController = new MediaControllerCompat(FullScreenPlayerActivity.this, token);
        if (mMediaController.getMetadata() == null) {
            finish();
            return;
        }

        mMediaController.registerCallback(mCallback);
        PlaybackStateCompat state = mMediaController.getPlaybackState();
        updatePlaybackState(state);
        MediaMetadataCompat metadata = mMediaController.getMetadata();
        if (metadata != null) {
            updateMediaDescription(metadata.getDescription());
            updateDuration(metadata);
        }
        updateProgress();
        if (state != null && (state.getState() == PlaybackStateCompat.STATE_PLAYING ||
                state.getState() == PlaybackStateCompat.STATE_BUFFERING)) {
            scheduleSeekbarUpdate();
        }

    } catch (RemoteException e) {
        e.printStackTrace();
    }
}
 
Example #11
Source File: MainActivity.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
private void connectToSession(MediaSessionCompat.Token token) throws RemoteException
{
    LogHelper.e(TAG, "connectToSession");
    MediaControllerCompat mediaController = new MediaControllerCompat(this, token);
    MediaControllerCompat.setMediaController(this, mediaController);

    mediaController.registerCallback(mediaControllerCallback);

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

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

    onMediaControllerConnected();
}
 
Example #12
Source File: ReadAloudService.java    From MyBookshelf with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 初始化MediaSession
 */
private void initMediaSession() {
    ComponentName mComponent = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mComponent);
    PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(this, 0,
            mediaButtonIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    mediaSessionCompat = new MediaSessionCompat(this, TAG, mComponent, mediaButtonReceiverPendingIntent);
    mediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
            return MediaButtonIntentReceiver.handleIntent(ReadAloudService.this, mediaButtonEvent);
        }
    });
    mediaSessionCompat.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
}
 
Example #13
Source File: MainActivity.java    From Android-9-Development-Cookbook with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MediaSessionCompat mediaSession =
            new MediaSessionCompat(this, getApplication().getPackageName());
    mediaSession.setCallback(mMediaSessionCallback);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mediaSession.setActive(true);
    PlaybackStateCompat state = new PlaybackStateCompat.Builder()
            .setActions(PlaybackStateCompat.ACTION_PLAY |
                    PlaybackStateCompat.ACTION_PLAY_PAUSE |
                    PlaybackStateCompat.ACTION_PAUSE |
                    PlaybackStateCompat.ACTION_SKIP_TO_NEXT |
                    PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS).build();
    mediaSession.setPlaybackState(state);
}
 
Example #14
Source File: MediaSessionPlaybackActivity.java    From android-PictureInPicture with Apache License 2.0 6 votes vote down vote up
private void initializeMediaSession() {
    mSession = new MediaSessionCompat(this, TAG);
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                    | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mSession.setActive(true);
    MediaControllerCompat.setMediaController(this, mSession.getController());

    MediaMetadataCompat metadata = new MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, mMovieView.getTitle())
            .build();
    mSession.setMetadata(metadata);

    MediaSessionCallback mMediaSessionCallback = new MediaSessionCallback(mMovieView);
    mSession.setCallback(mMediaSessionCallback);

    int state =
            mMovieView.isPlaying()
                    ? PlaybackStateCompat.STATE_PLAYING
                    : PlaybackStateCompat.STATE_PAUSED;
    updatePlaybackState(
            state,
            MEDIA_ACTIONS_ALL,
            mMovieView.getCurrentPosition(),
            mMovieView.getVideoResourceId());
}
 
Example #15
Source File: MediaSessionPlaybackActivity.java    From media-samples with Apache License 2.0 6 votes vote down vote up
private void initializeMediaSession() {
    mSession = new MediaSessionCompat(this, TAG);
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                    | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mSession.setActive(true);
    MediaControllerCompat.setMediaController(this, mSession.getController());

    MediaMetadataCompat metadata = new MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, mMovieView.getTitle())
            .build();
    mSession.setMetadata(metadata);

    MediaSessionCallback mMediaSessionCallback = new MediaSessionCallback(mMovieView);
    mSession.setCallback(mMediaSessionCallback);

    int state =
            mMovieView.isPlaying()
                    ? PlaybackStateCompat.STATE_PLAYING
                    : PlaybackStateCompat.STATE_PAUSED;
    updatePlaybackState(
            state,
            MEDIA_ACTIONS_ALL,
            mMovieView.getCurrentPosition(),
            mMovieView.getVideoResourceId());
}
 
Example #16
Source File: MediaStyleHelper.java    From AndroidAudioExample with MIT License 6 votes vote down vote up
/**
 * Build a notification using the information from the given media session. Makes heavy use
 * of {@link MediaMetadataCompat#getDescription()} to extract the appropriate information.
 *
 * @param context      Context used to construct the notification.
 * @param mediaSession Media session to get information.
 * @return A pre-built notification with information from the given media session.
 */
static NotificationCompat.Builder from(Context context, MediaSessionCompat mediaSession) {
    MediaControllerCompat controller = mediaSession.getController();
    MediaMetadataCompat mediaMetadata = controller.getMetadata();
    MediaDescriptionCompat description = mediaMetadata.getDescription();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setSubText(description.getDescription())
            .setLargeIcon(description.getIconBitmap())
            .setContentIntent(controller.getSessionActivity())
            .setDeleteIntent(
                    MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_STOP))
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    return builder;
}
 
Example #17
Source File: PlaybackControlBaseActivity.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
private void connectToSession(MediaSessionCompat.Token token) {
    try {
        LogUtils.d(TAG, "Session Token: " + token);
        mMediaController = new MediaControllerCompat(this, token);

        mMediaController.registerCallback(mMediaControllerCallback);

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

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

        onMediaControllerConnected();

    } catch (RemoteException ex) {
        LogUtils.e(TAG, ex.getMessage());
    }
}
 
Example #18
Source File: MediaNotificationManager.java    From 365browser with Apache License 2.0 6 votes vote down vote up
private MediaSessionCompat createMediaSession() {
    Context context = getContext();
    MediaSessionCompat mediaSession =
            new MediaSessionCompat(context, context.getString(R.string.app_name),
                    new ComponentName(context, getButtonReceiverClass()), null);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
            | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(mMediaSessionCallback);

    // TODO(mlamouri): the following code is to work around a bug that hopefully
    // MediaSessionCompat will handle directly. see b/24051980.
    try {
        mediaSession.setActive(true);
    } catch (NullPointerException e) {
        // Some versions of KitKat do not support AudioManager.registerMediaButtonIntent
        // with a PendingIntent. They will throw a NullPointerException, in which case
        // they should be able to activate a MediaSessionCompat with only transport
        // controls.
        mediaSession.setActive(false);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mediaSession.setActive(true);
    }
    return mediaSession;
}
 
Example #19
Source File: AudioBookPlayService.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 初始化MediaSession
 */
private void initMediaSession() {
    ComponentName mComponent = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mComponent);
    PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(this, 0,
            mediaButtonIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    mediaSessionCompat = new MediaSessionCompat(this, TAG, mComponent, mediaButtonReceiverPendingIntent);
    mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
            | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
            return MediaButtonIntentReceiver.handleIntent(mediaButtonEvent);
        }
    });
    mediaSessionCompat.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
    mediaSessionCompat.setActive(true);
}
 
Example #20
Source File: ReadAloudService.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 初始化MediaSession
 */
private void initMediaSession() {
    ComponentName mComponent = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mComponent);
    PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(this, 0,
            mediaButtonIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    mediaSessionCompat = new MediaSessionCompat(this, TAG, mComponent, mediaButtonReceiverPendingIntent);
    mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
            | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
            return MediaButtonIntentReceiver.handleIntent(mediaButtonEvent);
        }
    });
    mediaSessionCompat.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
}
 
Example #21
Source File: MusicService.java    From VinylMusicPlayer with GNU General Public License v3.0 6 votes vote down vote up
private void setupMediaSession() {
    ComponentName mediaButtonReceiverComponentName = new ComponentName(getApplicationContext(), MediaButtonIntentReceiver.class);

    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mediaButtonReceiverComponentName);

    PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0);
    mMediaSessionCallback = new MediaSessionCallback(this, getApplicationContext());
    mediaSession = new MediaSessionCompat(this, "VinylMusicPlayer", mediaButtonReceiverComponentName, mediaButtonReceiverPendingIntent);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
            | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mediaSession.setCallback(mMediaSessionCallback);
    mediaSession.setActive(true);
    mediaSession.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
    setSessionToken(mediaSession.getSessionToken());
}
 
Example #22
Source File: QueueHelper.java    From LyricHere with Apache License 2.0 5 votes vote down vote up
public static int getMusicIndexOnQueue(Iterable<MediaSessionCompat.QueueItem> queue,
                                       String mediaId) {
    int index = 0;
    for (MediaSessionCompat.QueueItem item : queue) {
        if (mediaId.equals(item.getDescription().getMediaId())) {
            return index;
        }
        index++;
    }
    return -1;
}
 
Example #23
Source File: MediaSessionModule.java    From PainlessMusicPlayer with Apache License 2.0 5 votes vote down vote up
@Provides
MediaSessionCompat.Callback provideMediaSessionCallback(
        @NonNull final QueueProviderMediaBrowser queueProviderMediaBrowser,
        @NonNull final MediaIdPlaybackInitializer mediaIdPlaybackInitializer,
        @NonNull final PlaybackInitializer playbackInitializer,
        @NonNull final PlaybackServiceControl playbackServiceControl,
        @NonNull final SearchPlaybackInitializer searchPlaybackInitializer) {
    return new MediaSessionCallback(
            mediaIdPlaybackInitializer,
            playbackInitializer,
            playbackServiceControl,
            queueProviderMediaBrowser,
            searchPlaybackInitializer);
}
 
Example #24
Source File: PlayerService.java    From Prodigal with Apache License 2.0 5 votes vote down vote up
private void initMediaSession() {
        ComponentName mediaButtonReceiver = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);
        mediaSession = new MediaSessionCompat(getApplicationContext(), "PrdPlayer", mediaButtonReceiver, null);
//        mediaSession.setCallback(mMediaSessionCallback);
        mediaSession.setFlags( MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS );

        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setClass(this, MediaButtonReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
        mediaSession.setMediaButtonReceiver(pendingIntent);
        setSessionToken(mediaSession.getSessionToken());

    }
 
Example #25
Source File: MediaSessionFactoryImpl.java    From PainlessMusicPlayer with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public MediaSessionCompat newMediaSession() {
    final MediaSessionCompat mediaSession = new MediaSessionCompat(
            context, TAG_MEDIA_SESSION, mediaButtonReceiver, mediaButtonIntent);
    mediaSession.setCallback(mediaSessionCallback);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
            MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setSessionActivity(PendingIntent.getActivity(context, 1,
            new Intent(context, sessionActivityClass), PendingIntent.FLAG_UPDATE_CURRENT));
    mediaSession.setActive(true);
    return mediaSession;
}
 
Example #26
Source File: QueueHelper.java    From LyricHere with Apache License 2.0 5 votes vote down vote up
public static List<MediaSessionCompat.QueueItem> getPlayingQueueFromSearch(String query,
                                                                           Bundle queryParams, MusicProvider musicProvider) {

    LogUtils.d(TAG, "Creating playing queue for musics from search: ", query,
            " params=", queryParams);

    VoiceSearchParams params = new VoiceSearchParams(query, queryParams);

    LogUtils.d(TAG, "VoiceSearchParams: ", params);

    if (params.isAny) {
        // If isAny is true, we will play anything. This is app-dependent, and can be,
        // for example, favorite playlists, "I'm feeling lucky", most recent, etc.
        return getRandomQueue(musicProvider);
    }

    Iterable<MediaMetadataCompat> result = null;
    if (params.isAlbumFocus) {
        result = musicProvider.searchMusicByAlbum(params.album);
    } else if (params.isGenreFocus) {
        result = musicProvider.getMusicsByGenre(params.genre);
    } else if (params.isArtistFocus) {
        result = musicProvider.searchMusicByArtist(params.artist);
    } else if (params.isSongFocus) {
        result = musicProvider.searchMusicBySongTitle(params.song);
    }

    // If there was no results using media focus parameter, we do an unstructured query.
    // This is useful when the user is searching for something that looks like an artist
    // to Google, for example, but is not. For example, a user searching for Madonna on
    // a PodCast application wouldn't get results if we only looked at the
    // Artist (podcast author). Then, we can instead do an unstructured search.
    if (params.isUnstructured || result == null || !result.iterator().hasNext()) {
        // To keep it simple for this example, we do unstructured searches on the
        // song title only. A real world application could search on other fields as well.
        result = musicProvider.searchMusicBySongTitle(query);
    }

    return convertToQueue(result, MEDIA_ID_MUSICS_BY_SEARCH, query);
}
 
Example #27
Source File: MediaSessionFactoryImpl.java    From PainlessMusicPlayer with Apache License 2.0 5 votes vote down vote up
public MediaSessionFactoryImpl(
        @NonNull final Context context,
        @NonNull final Class<? extends Activity> sessionActivityClass,
        @NonNull final MediaSessionCompat.Callback mediaSessionCallback) {
    this.context = context;
    this.sessionActivityClass = sessionActivityClass;
    this.mediaSessionCallback = mediaSessionCallback;

    this.mediaButtonReceiver = new ComponentName(context, MediaButtonReceiver.class);
    this.mediaButtonIntent = PendingIntent.getBroadcast(
            context,
            1,
            new Intent(context, MediaButtonReceiver.class),
            PendingIntent.FLAG_UPDATE_CURRENT);
}
 
Example #28
Source File: MainActivity.java    From lbry-android with MIT License 5 votes vote down vote up
public void initMediaSession() {
    ComponentName mediaButtonReceiver = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);
    mediaSession = new MediaSessionCompat(getApplicationContext(), "LBRYMediaSession", mediaButtonReceiver, null);
    MediaSessionConnector connector = new MediaSessionConnector(mediaSession);
    connector.setPlayer(MainActivity.appPlayer);
    mediaSession.setActive(true);
}
 
Example #29
Source File: MusicService.java    From Muzesto with GNU General Public License v3.0 5 votes vote down vote up
private void setUpMediaSession() {
    mSession = new MediaSessionCompat(this, "Timber");
    mSession.setCallback(new MediaSessionCompat.Callback() {
        @Override
        public void onPause() {
            pause();
            mPausedByTransientLossOfFocus = false;
        }

        @Override
        public void onPlay() {
            play();
        }

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

        @Override
        public void onSkipToNext() {
            gotoNext(true);
        }

        @Override
        public void onSkipToPrevious() {
            prev(false);
        }

        @Override
        public void onStop() {
            pause();
            mPausedByTransientLossOfFocus = false;
            seek(0);
            releaseServiceUiAndStop();
        }
    });
    mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
}
 
Example #30
Source File: MediaStyleHelper.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build a notification using the information from the given media session. Makes heavy use
 * of {@link MediaMetadataCompat#getDescription()} to extract the appropriate information.
 * @param context Context used to construct the notification.
 * @param mediaSession Media session to get information.
 * @return A pre-built notification with information from the given media session.
 */
public static NotificationCompat.Builder from(
        Context context, MediaSessionCompat mediaSession) {
    MediaControllerCompat controller = mediaSession.getController();
    if (controller == null) {
        return null;
    }
    MediaMetadataCompat mediaMetadata = controller.getMetadata();
    if (mediaMetadata == null) {
        return null;

    }

    MediaDescriptionCompat description = mediaMetadata.getDescription();
    if (description == null) {
        return null;
    }

 
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, BackgroundAudioService.CHANNEL_ID);
    builder
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setSubText(description.getDescription())
            .setLargeIcon(description.getIconBitmap())
            .setContentIntent(controller.getSessionActivity())

            .setDeleteIntent(
                    MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_STOP))
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    return builder;
}