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

The following java examples will help you to understand the usage of android.support.v4.media.session.MediaSessionCompat. These source code samples are taken from different open source projects.

Example 1
Project: notification-master  File: MediaBuilder.java View source code
@Override
public void build() {
    super.build();
    NotificationCompat.MediaStyle style = new NotificationCompat.MediaStyle();
    style.setMediaSession(new MediaSessionCompat(NotifyUtil.context, "MediaSession", new ComponentName(NotifyUtil.context, Intent.ACTION_MEDIA_BUTTON), null).getSessionToken());
    //设置�现实在通知�方的图标 最多三个
    style.setShowActionsInCompactView(2, 3);
    style.setShowCancelButton(true);
    cBuilder.setStyle(style);
    cBuilder.setShowWhen(false);
}
Example 2
Project: Jockey-master  File: MusicPlayer.java View source code
/**
     * Initiate a MediaSession to allow the Android system to interact with the player
     */
private void initMediaSession() {
    Timber.i("Initializing MediaSession");
    MediaSessionCompat session = new MediaSessionCompat(mContext, TAG, null, null);
    session.setCallback(new MediaSessionCallback(this));
    session.setSessionActivity(PendingIntent.getActivity(mContext, 0, MainActivity.newNowPlayingIntent(mContext).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_CANCEL_CURRENT));
    session.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder().setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS | PlaybackStateCompat.ACTION_STOP).setState(PlaybackStateCompat.STATE_NONE, 0, 0f);
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setClass(mContext, MediaButtonReceiver.class);
    PendingIntent mbrIntent = PendingIntent.getBroadcast(mContext, 0, mediaButtonIntent, 0);
    session.setMediaButtonReceiver(mbrIntent);
    session.setPlaybackState(state.build());
    session.setActive(true);
    mMediaSession = session;
}
Example 3
Project: Sunami-master  File: TheBrain.java View source code
// Registers audio and media session
private void registerAudio() {
    if (mHasAudioFocus || !mIsInit) {
        return;
    }
    mHasAudioFocus = true;
    // Add audio focus change listener
    mAFChangeListener = new AudioManager.OnAudioFocusChangeListener() {

        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                pausePlayback();
                setUI(false);
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // Does nothing cause made me play music at work
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                pausePlayback();
                unregisterAudio();
                setUI(false);
            }
        }
    };
    mAudioManager.requestAudioFocus(mAFChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    // Add headphone out listener
    registerReceiver(mNoisyAudioStreamReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
    // Add notification and transport controls
    ComponentName eventReceiver = new ComponentName(getPackageName(), RemoteControlEventReceiver.class.getName());
    mSession = new MediaSessionCompat(this, "FireSession", eventReceiver, null);
    mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mSession.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
    mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_TITLE, "").putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, "").putLong(MediaMetadata.METADATA_KEY_DURATION, -1).build());
    mSession.setCallback(new MediaSessionCompat.Callback() {

        @Override
        public void onSeekTo(long pos) {
            super.onSeekTo(pos);
            setProgress((int) pos, isPlaying());
        }
    });
    mSession.setActive(true);
}
Example 4
Project: android-UniversalMusicPlayer-master  File: MusicService.java View source code
/*
     * (non-Javadoc)
     * @see android.app.Service#onCreate()
     */
@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);
    mPackageValidator = new PackageValidator(this);
    QueueManager queueManager = new QueueManager(mMusicProvider, getResources(), new QueueManager.MetadataUpdateListener() {

        @Override
        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);
    }
    int playServicesAvailable = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
    if (!TvHelper.isTvUiMode(this) && playServicesAvailable == ConnectionResult.SUCCESS) {
        mCastSessionManager = CastContext.getSharedInstance(this).getSessionManager();
        mCastSessionManagerListener = new CastSessionManagerListener();
        mCastSessionManager.addSessionManagerListener(mCastSessionManagerListener, CastSession.class);
    }
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
    registerCarConnectionReceiver();
}
Example 5
Project: platform_frameworks_support-master  File: MediaRouter.java View source code
public void setMediaSessionCompat(final MediaSessionCompat session) {
    mCompatSession = session;
    if (android.os.Build.VERSION.SDK_INT >= 21) {
        setMediaSessionRecord(session != null ? new MediaSessionRecord(session) : null);
    } else if (android.os.Build.VERSION.SDK_INT >= 14) {
        if (mRccMediaSession != null) {
            removeRemoteControlClient(mRccMediaSession.getRemoteControlClient());
            mRccMediaSession.removeOnActiveChangeListener(mSessionActiveListener);
        }
        mRccMediaSession = session;
        if (session != null) {
            session.addOnActiveChangeListener(mSessionActiveListener);
            if (session.isActive()) {
                addRemoteControlClient(session.getRemoteControlClient());
            }
        }
    }
}
Example 6
Project: ponyville-live-android-master  File: FullScreenPlayerActivity.java View source code
private void connectToSession(MediaSessionCompat.Token token) {
    MediaControllerCompat controller = null;
    try {
        controller = new MediaControllerCompat(FullScreenPlayerActivity.this, token);
    } catch (RemoteException e) {
        Timber.e(TAG, "connectToSession", e);
        finish();
        return;
    }
    if (controller.getMetadata() == null) {
        finish();
        return;
    }
    setMediaControllerCompat(controller);
    controller.registerCallback(callback);
    PlaybackStateCompat state = controller.getPlaybackState();
    updatePlaybackState(state);
    MediaMetadataCompat metadata = controller.getMetadata();
    if (metadata != null) {
        updateMediaDescription(metadata.getDescription());
    }
}
Example 7
Project: bikey-master  File: MediaButtonHandler.java View source code
@MainThread
public void start(Context context) {
    Log.d();
    if (mMediaSessionCompat != null) {
        mMediaSessionCompat.setActive(false);
        mMediaSessionCompat.release();
    }
    mMediaSessionCompat = new MediaSessionCompat(context, TAG);
    mMediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mMediaSessionCompat.setCallback(new BikeyMediaButtonCallback(context));
    mMediaSessionCompat.setActive(true);
}
Example 8
Project: LyricHere-master  File: MusicService.java View source code
@Override
public void onCreate() {
    super.onCreate();
    LogUtils.d(TAG, "onCreate");
    mPlayingQueue = new ArrayList<>();
    mMusicProvider = new MusicProvider();
    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 {
        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, MusicPlayerActivity.class);
    PendingIntent pi = PendingIntent.getActivity(context, 99, /*request code*/
    intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mSession.setSessionActivity(pi);
    mSessionExtras = new Bundle();
    mSession.setExtras(mSessionExtras);
    updatePlaybackState(null);
    mMediaNotificationManager = new MediaNotificationManager(this);
}
Example 9
Project: sdk-support-master  File: MediaControllerCompat.java View source code
@Override
public void handleMessage(Message msg) {
    if (!mRegistered) {
        return;
    }
    switch(msg.what) {
        case MSG_EVENT:
            onSessionEvent((String) msg.obj, msg.getData());
            break;
        case MSG_UPDATE_PLAYBACK_STATE:
            onPlaybackStateChanged((PlaybackStateCompat) msg.obj);
            break;
        case MSG_UPDATE_METADATA:
            onMetadataChanged((MediaMetadataCompat) msg.obj);
            break;
        case MSG_UPDATE_QUEUE:
            onQueueChanged((List<MediaSessionCompat.QueueItem>) msg.obj);
            break;
        case MSG_UPDATE_QUEUE_TITLE:
            onQueueTitleChanged((CharSequence) msg.obj);
            break;
        case MSG_UPDATE_EXTRAS:
            onExtrasChanged((Bundle) msg.obj);
            break;
        case MSG_UPDATE_VOLUME:
            onAudioInfoChanged((PlaybackInfo) msg.obj);
            break;
        case MSG_DESTROYED:
            onSessionDestroyed();
            break;
    }
}
Example 10
Project: androidtv-Leanback-master  File: PlaybackOverlayFragment.java View source code
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    if (cursor != null && cursor.moveToFirst()) {
        switch(loader.getId()) {
            case QUEUE_VIDEOS_LOADER:
                {
                    mQueue.clear();
                    while (!cursor.isAfterLast()) {
                        Video v = (Video) mVideoCursorMapper.convert(cursor);
                        // Set the queue index to the selected video.
                        if (v.id == mSelectedVideo.id) {
                            mQueueIndex = mQueue.size();
                        }
                        // Add the video to the queue.
                        MediaSessionCompat.QueueItem item = getQueueItem(v);
                        mQueue.add(item);
                        cursor.moveToNext();
                    }
                    mSession.setQueue(mQueue);
                    mSession.setQueueTitle(getString(R.string.queue_name));
                    break;
                }
            case RECOMMENDED_VIDEOS_LOADER:
                {
                    mVideoCursorAdapter.changeCursor(cursor);
                    break;
                }
            default:
                {
                    // Playing a specific video.
                    Video video = (Video) mVideoCursorMapper.convert(cursor);
                    playVideo(video, mAutoPlayExtras);
                    break;
                }
        }
    }
}
Example 11
Project: GEM-master  File: MediaService.java View source code
public void setUp() {
    mPlayback = PlaybackManager.from(this);
    mNotification = new MediaNotification(this);
    mPlayback.mNotification = mNotification;
    mPlayback.registerListener(this);
    mButtonReceiver = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mButtonReceivedIntent = PendingIntent.getBroadcast(this, 0, new Intent(Intent.ACTION_MEDIA_BUTTON), PendingIntent.FLAG_UPDATE_CURRENT);
    mSession = new MediaSessionCompat(this, TAG);
    mSession.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
    mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mSession.setCallback(new MediaSessionCallback());
    setState(STATE_NONE);
    mSession.setMediaButtonReceiver(mButtonReceivedIntent);
}
Example 12
Project: android-support-v4-master  File: MediaControllerCompat.java View source code
@Override
public void handleMessage(Message msg) {
    if (!mRegistered) {
        return;
    }
    switch(msg.what) {
        case MSG_EVENT:
            onSessionEvent((String) msg.obj, msg.getData());
            break;
        case MSG_UPDATE_PLAYBACK_STATE:
            onPlaybackStateChanged((PlaybackStateCompat) msg.obj);
            break;
        case MSG_UPDATE_METADATA:
            onMetadataChanged((MediaMetadataCompat) msg.obj);
            break;
        case MSG_UPDATE_QUEUE:
            onQueueChanged((List<MediaSessionCompat.QueueItem>) msg.obj);
            break;
        case MSG_UPDATE_QUEUE_TITLE:
            onQueueTitleChanged((CharSequence) msg.obj);
            break;
        case MSG_UPDATE_EXTRAS:
            onExtrasChanged((Bundle) msg.obj);
            break;
        case MSG_UPDATE_VOLUME:
            onAudioInfoChanged((PlaybackInfo) msg.obj);
            break;
        case MSG_DESTROYED:
            onSessionDestroyed();
            break;
    }
}
Example 13
Project: News-Android-App-master  File: PodcastNotification.java View source code
private void initMediaSessions() {
    String packageName = PodcastNotificationToggle.class.getPackage().getName();
    ComponentName receiver = new ComponentName(packageName, PodcastNotificationToggle.class.getName());
    mSession = new MediaSessionCompat(mContext, "PlayerService", receiver, null);
    mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_PAUSED, 0, 0).setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
    MediaItem podcastItem = ((PodcastPlaybackService) mContext).getCurrentlyPlayingPodcast();
    String favIconUrl = podcastItem.favIcon;
    DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.default_feed_icon_light).showImageForEmptyUri(R.drawable.default_feed_icon_light).showImageOnFail(R.drawable.default_feed_icon_light).build();
    Bitmap bmpAlbumArt = ImageLoader.getInstance().loadImageSync(favIconUrl, displayImageOptions);
    mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "Test").putString(MediaMetadataCompat.METADATA_KEY_ALBUM, "Test").putString(MediaMetadataCompat.METADATA_KEY_TITLE, "Test").putLong(//.putString(MediaMetadataCompat.METADATA_KEY_TITLE, podcastItem.title)
    MediaMetadataCompat.METADATA_KEY_DURATION, 100).putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bmpAlbumArt).build());
    mSession.setCallback(new MediaSessionCallback());
    AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    audioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() {

        @Override
        public void onAudioFocusChange(int focusChange) {
        // Ignore
        }
    }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    //MediaControllerCompat controller = mSession.getController();
    mSession.setActive(true);
}
Example 14
Project: odyssey-master  File: OdysseyNotificationManager.java View source code
/*
     * Creates a android system notification with two different remoteViews. One
     * for the normal layout and one for the big one. Sets the different
     * attributes of the remoteViews and starts a thread for Cover generation.
     */
public void updateNotification(TrackModel track, PlaybackService.PLAYSTATE state, MediaSessionCompat.Token mediaSessionToken) {
    if (track != null) {
        mNotificationBuilder = new NotificationCompat.Builder(mContext);
        // Open application intent
        Intent contentIntent = new Intent(mContext, OdysseyMainActivity.class);
        contentIntent.putExtra(OdysseyMainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW, OdysseyMainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW_NOWPLAYINGVIEW);
        contentIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NO_HISTORY);
        PendingIntent contentPendingIntent = PendingIntent.getActivity(mContext, NOTIFICATION_INTENT_OPENGUI, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setContentIntent(contentPendingIntent);
        // Set pendingintents
        // Previous song action
        Intent prevIntent = new Intent(PlaybackService.ACTION_PREVIOUS);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PREVIOUS, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action prevAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_previous_48dp, "Previous", prevPendingIntent).build();
        // Pause/Play action
        PendingIntent playPauseIntent;
        int playPauseIcon;
        if (state == PlaybackService.PLAYSTATE.PLAYING) {
            Intent pauseIntent = new Intent(PlaybackService.ACTION_PAUSE);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_pause_48dp;
        } else {
            Intent playIntent = new Intent(PlaybackService.ACTION_PLAY);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, playIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_play_arrow_48dp;
        }
        NotificationCompat.Action playPauseAction = new NotificationCompat.Action.Builder(playPauseIcon, "PlayPause", playPauseIntent).build();
        // Next song action
        Intent nextIntent = new Intent(PlaybackService.ACTION_NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_NEXT, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action nextAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_next_48dp, "Next", nextPendingIntent).build();
        // Quit action
        Intent quitIntent = new Intent(PlaybackService.ACTION_QUIT);
        PendingIntent quitPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_QUIT, quitIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setDeleteIntent(quitPendingIntent);
        mNotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        mNotificationBuilder.setSmallIcon(R.drawable.odyssey_notification);
        mNotificationBuilder.addAction(prevAction);
        mNotificationBuilder.addAction(playPauseAction);
        mNotificationBuilder.addAction(nextAction);
        NotificationCompat.MediaStyle notificationStyle = new NotificationCompat.MediaStyle();
        notificationStyle.setShowActionsInCompactView(1, 2);
        notificationStyle.setMediaSession(mediaSessionToken);
        mNotificationBuilder.setStyle(notificationStyle);
        mNotificationBuilder.setContentTitle(track.getTrackName());
        mNotificationBuilder.setContentText(track.getTrackArtistName());
        // Remove unnecessary time info
        mNotificationBuilder.setWhen(0);
        // Cover but only if changed
        if (mLastTrack == null || !track.getTrackAlbumKey().equals(mLastTrack.getTrackAlbumKey())) {
            mLastTrack = track;
            mLastBitmap = null;
        }
        // Only set image if an saved one is available
        if (mLastBitmap != null && !mHideArtwork) {
            mNotificationBuilder.setLargeIcon(mLastBitmap);
        } else {
            /**
                 * Create a dummy placeholder image for versions greater android 7 because it
                 * does not automatically show the application icon anymore in mediastyle notifications.
                 */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Drawable icon = mContext.getDrawable(R.drawable.notification_placeholder_256dp);
                Bitmap iconBitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(iconBitmap);
                DrawFilter filter = new PaintFlagsDrawFilter(Paint.ANTI_ALIAS_FLAG, 1);
                canvas.setDrawFilter(filter);
                icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                icon.setFilterBitmap(true);
                icon.draw(canvas);
                mNotificationBuilder.setLargeIcon(iconBitmap);
            } else {
                /**
                     * For older android versions set the null icon which will result in a dummy icon
                     * generated from the application icon.
                     */
                mNotificationBuilder.setLargeIcon(null);
            }
        }
        // Build the notification
        mNotification = mNotificationBuilder.build();
        // Pause notification should be dismissible.
        if (mContext instanceof Service) {
            if (state == PlaybackService.PLAYSTATE.PLAYING) {
                ((Service) mContext).startForeground(NOTIFICATION_ID, mNotification);
            } else {
                ((Service) mContext).stopForeground(false);
            }
        }
        // Send the notification away
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }
}
Example 15
Project: torrenttunes-android-master  File: MusicService.java View source code
/*
     * (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);
    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 {
        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());
}
Example 16
Project: Now-Playing-master  File: MusicControlModule.java View source code
public void init() {
    INSTANCE = this;
    ReactApplicationContext context = getReactApplicationContext();
    ComponentName compName = new ComponentName(context, MusicControlReceiver.class);
    session = new MediaSessionCompat(context, "MusicControl", compName, null);
    session.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    session.setCallback(new MusicControlListener(context));
    volume = new MusicControlListener.VolumeListener(context, true, 100, 100);
    if (remoteVolume) {
        session.setPlaybackToRemote(volume);
    } else {
        session.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
    }
    md = new MediaMetadataCompat.Builder();
    pb = new PlaybackStateCompat.Builder();
    pb.setActions(controls);
    nb = new NotificationCompat.Builder(context);
    nb.setStyle(new NotificationCompat.MediaStyle().setMediaSession(session.getSessionToken()));
    state = pb.build();
    notification = new MusicControlNotification(context);
    notification.updateActions(controls);
    IntentFilter filter = new IntentFilter();
    filter.addAction(MusicControlNotification.REMOVE_NOTIFICATION);
    filter.addAction(MusicControlNotification.MEDIA_BUTTON);
    filter.addAction(Intent.ACTION_MEDIA_BUTTON);
    receiver = new MusicControlReceiver(this, context.getPackageName());
    context.registerReceiver(receiver, filter);
    context.startService(new Intent(context, MusicControlNotification.NotificationService.class));
    context.registerComponentCallbacks(this);
    isPlaying = false;
    init = true;
}
Example 17
Project: tomahawk-android-master  File: PlaybackService.java View source code
private void initMediaSession() {
    ComponentName componentName = new ComponentName(this, MediaButtonReceiver.class);
    mMediaSession = new MediaSessionCompat(getApplicationContext(), "Tomahawk", componentName, null);
    mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    Intent intent = new Intent(PlaybackService.this, TomahawkMainActivity.class);
    intent.setAction(TomahawkMainActivity.SHOW_PLAYBACKFRAGMENT_ON_STARTUP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(PlaybackService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mMediaSession.setSessionActivity(pendingIntent);
    HandlerThread thread = new HandlerThread("playbackservice_callback");
    thread.start();
    mCallbackHandler = new Handler(thread.getLooper());
    mMediaSession.setCallback(mMediaSessionCallback, mCallbackHandler);
    mMediaSession.setRatingType(RatingCompat.RATING_HEART);
    Bundle extras = new Bundle();
    extras.putString(EXTRAS_KEY_PLAYBACKMANAGER, mPlaybackManager.getId());
    mMediaSession.setExtras(extras);
    updateMediaPlayState();
    setSessionToken(mMediaSession.getSessionToken());
    MediaImageHelper.get().addListener(mMediaImageLoadedListener);
}
Example 18
Project: VoiceControlForPlex-master  File: VoiceControlForPlexApplication.java View source code
public void setNotification(final PlexClient client, final PlayerState currentState, final PlexMedia media, final ArrayList<? extends PlexMedia> playlist, final MediaSessionCompat mediaSession) {
    if (client == null) {
        logger.d("Client is null for some reason");
        return;
    }
    if (client.isLocalDevice())
        return;
    final int[] numBitmapsFetched = new int[] { 0 };
    final int[] numBitmapsToFetch = new int[] { 0 };
    // Figure out which track in the playlist this is, to know whether or not to set up the Intent to handle previous/next
    final int[] playlistIndexF = new int[1];
    for (int i = 0; i < playlist.size(); i++) {
        //      logger.d("comparing %s to %s (%s)", playlist.get(i).key, media.key, playlist.get(i).key.equals(media.key));
        if (playlist.get(i).equals(media)) {
            //        logger.d("found a match for %s", media.key);
            playlistIndexF[0] = i;
            break;
        }
    }
    final int playlistIndex = playlistIndexF[0];
    PlexMedia.IMAGE_KEY keyIcon = media instanceof PlexTrack ? PlexMedia.IMAGE_KEY.NOTIFICATION_THUMB_MUSIC_BIG : PlexMedia.IMAGE_KEY.NOTIFICATION_THUMB_BIG;
    PlexMedia.IMAGE_KEY keyBackground = media instanceof PlexTrack ? PlexMedia.IMAGE_KEY.NOTIFICATION_MUSIC_BACKGROUND : PlexMedia.IMAGE_KEY.NOTIFICATION_BACKGROUND;
    final Bitmap[] bitmapsFetched = new Bitmap[2];
    final Runnable onFinished = () -> {
        // this is where the magic happens!
        android.content.Intent playIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
        playIntent.setAction(Intent.ACTION_PLAY);
        playIntent.putExtra(SubscriptionService.CLIENT, client);
        playIntent.putExtra(SubscriptionService.MEDIA, media);
        playIntent.putParcelableArrayListExtra(Intent.EXTRA_PLAYLIST, playlist);
        PendingIntent playPendingIntent = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, playIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        android.content.Intent pauseIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
        pauseIntent.setAction(Intent.ACTION_PAUSE);
        pauseIntent.putExtra(SubscriptionService.CLIENT, client);
        pauseIntent.putExtra(SubscriptionService.MEDIA, media);
        pauseIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
        PendingIntent pausePendingIntent = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        android.content.Intent disconnectIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
        disconnectIntent.setAction(Intent.ACTION_DISCONNECT);
        disconnectIntent.putExtra(SubscriptionService.CLIENT, client);
        disconnectIntent.putExtra(SubscriptionService.MEDIA, media);
        disconnectIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
        PendingIntent piDisconnect = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, disconnectIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        android.content.Intent nowPlayingIntent = new android.content.Intent(VoiceControlForPlexApplication.this, MainActivity.class);
        nowPlayingIntent.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK | android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK);
        nowPlayingIntent.setAction(MainActivity.ACTION_SHOW_NOW_PLAYING);
        nowPlayingIntent.putExtra(Intent.EXTRA_MEDIA, media);
        nowPlayingIntent.putExtra(Intent.EXTRA_CLIENT, client);
        nowPlayingIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
        PendingIntent piNowPlaying = PendingIntent.getActivity(VoiceControlForPlexApplication.this, 0, nowPlayingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        android.content.Intent rewindIntent;
        android.content.Intent forwardIntent;
        android.content.Intent previousIntent;
        android.content.Intent nextIntent;
        List<NotificationCompat.Action> actions = new ArrayList<>();
        if (!media.isMusic()) {
            rewindIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
            rewindIntent.setAction(Intent.ACTION_REWIND);
            rewindIntent.putExtra(SubscriptionService.CLIENT, client);
            rewindIntent.putExtra(SubscriptionService.MEDIA, media);
            rewindIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
            PendingIntent piRewind = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, rewindIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            forwardIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
            forwardIntent.setAction(Intent.ACTION_FORWARD);
            forwardIntent.putExtra(SubscriptionService.CLIENT, client);
            forwardIntent.putExtra(SubscriptionService.MEDIA, media);
            forwardIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
            PendingIntent piForward = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, forwardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_rewind, "Rewind", piRewind).build());
            if (currentState == PlayerState.PAUSED)
                actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_play, "Play", playPendingIntent).build());
            else
                actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_pause, "Pause", pausePendingIntent).build());
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_forward, "Fast Forward", piForward).build());
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_disconnect, "Disconnect", piDisconnect).build());
        } else {
            PendingIntent piPrevious = null;
            if (playlistIndex > 0) {
                previousIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
                previousIntent.setAction(Intent.ACTION_PREVIOUS);
                previousIntent.putExtra(SubscriptionService.CLIENT, client);
                previousIntent.putExtra(SubscriptionService.MEDIA, media);
                previousIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
                piPrevious = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, previousIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            }
            PendingIntent piNext = null;
            if (playlistIndex + 1 < playlist.size()) {
                nextIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
                nextIntent.setAction(Intent.ACTION_NEXT);
                nextIntent.putExtra(SubscriptionService.CLIENT, client);
                nextIntent.putExtra(SubscriptionService.MEDIA, media);
                nextIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
                piNext = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            }
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_previous, "Previous", piPrevious).build());
            if (currentState == PlayerState.PAUSED)
                actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_play, "Play", playPendingIntent).build());
            else
                actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_pause, "Pause", pausePendingIntent).build());
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_next, "Next", piNext).build());
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_disconnect, "Disconnect", piDisconnect).build());
        }
        Notification n;
        NotificationCompat.Builder builder = new NotificationCompat.Builder(VoiceControlForPlexApplication.this);
        // Show controls on lock screen even when user hides sensitive content.
        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setSmallIcon(R.drawable.vcfp_notification).setAutoCancel(false).setOngoing(true).setOnlyAlertOnce(true).setDefaults(Notification.DEFAULT_ALL).setStyle(// Apply the media style template
        new NotificationCompat.MediaStyle().setShowActionsInCompactView(0, 1, 2).setMediaSession(mediaSession.getSessionToken())).setContentTitle(media.getNotificationTitle()).setContentText(media.getNotificationSubtitle()).setContentIntent(piNowPlaying).setLargeIcon(bitmapsFetched[0]);
        for (NotificationCompat.Action action : actions) {
            builder.addAction(action);
        }
        n = builder.build();
        try {
            // Disable notification sound
            n.defaults = 0;
            mNotifyMgr.notify(nowPlayingNotificationId, n);
            Logger.d("Notification set");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        mediaSession.setMetadata(new MediaMetadataCompat.Builder().putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmapsFetched[1]).putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, media.art).putString(MediaMetadataCompat.METADATA_KEY_ARTIST, media.getNotificationTitle()).build());
        mediaSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(currentState == PlayerState.PAUSED ? PlaybackStateCompat.STATE_PAUSED : PlaybackStateCompat.STATE_PLAYING, Long.parseLong(media.viewOffset), 1f).build());
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    };
    // Check if the bitmaps have already been fetched. If they have, launch the runnable to set the notification
    Bitmap bitmap = getCachedBitmap(media.getImageKey(keyIcon));
    Bitmap bigBitmap = getCachedBitmap(media.getImageKey(keyBackground));
    if (bitmap != null && bigBitmap != null) {
        bitmapsFetched[0] = bitmap;
        bitmapsFetched[1] = bigBitmap;
        onFinished.run();
    } else {
        ArrayList<FetchMediaImageTask> taskList = new ArrayList<>();
        if (media.getNotificationThumb(keyIcon) != null) {
            numBitmapsToFetch[0]++;
            // Fetch both (big and regular) versions of the notification bitmap, and when both are finished, launch the runnable above that will set the notification
            taskList.add(new FetchMediaImageTask(media, PlexMedia.IMAGE_SIZES.get(keyIcon)[0], PlexMedia.IMAGE_SIZES.get(keyIcon)[1], media.getNotificationThumb(keyIcon), media.getImageKey(keyIcon), new BitmapHandler() {

                @Override
                public void onSuccess(Bitmap bitmap) {
                    bitmapsFetched[0] = bitmap;
                    if (numBitmapsFetched[0] + 1 == numBitmapsToFetch[0])
                        onFinished.run();
                    numBitmapsFetched[0]++;
                }
            }));
        }
        if (media.getNotificationThumb(keyBackground) != null) {
            numBitmapsToFetch[0]++;
            taskList.add(new FetchMediaImageTask(media, PlexMedia.IMAGE_SIZES.get(keyBackground)[0], PlexMedia.IMAGE_SIZES.get(keyBackground)[1], media.getNotificationThumb(keyBackground), media.getImageKey(keyBackground), new BitmapHandler() {

                @Override
                public void onSuccess(Bitmap bitmap) {
                    bitmapsFetched[1] = bitmap;
                    if (numBitmapsFetched[0] + 1 == numBitmapsToFetch[0])
                        onFinished.run();
                    numBitmapsFetched[0]++;
                }
            }));
        }
        if (taskList.size() == 0)
            onFinished.run();
        else
            for (FetchMediaImageTask task : taskList) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}
Example 19
Project: android-sdk-sources-for-api-level-23-master  File: MediaRouter.java View source code
public void setMediaSessionCompat(final MediaSessionCompat session) {
    mCompatSession = session;
    if (android.os.Build.VERSION.SDK_INT >= 21) {
        setMediaSession(session != null ? session.getMediaSession() : null);
    } else if (android.os.Build.VERSION.SDK_INT >= 14) {
        if (mRccMediaSession != null) {
            removeRemoteControlClient(mRccMediaSession.getRemoteControlClient());
            mRccMediaSession.removeOnActiveChangeListener(mSessionActiveListener);
        }
        mRccMediaSession = session;
        if (session != null) {
            session.addOnActiveChangeListener(mSessionActiveListener);
            if (session.isActive()) {
                addRemoteControlClient(session.getRemoteControlClient());
            }
        }
    }
}
Example 20
Project: AndroidChromium-master  File: MediaNotificationManager.java View source code
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);
    // MediaSessionCompat will handle directly. see b/24051980.
    try {
        mediaSession.setActive(true);
    } catch (NullPointerException e) {
        mediaSession.setActive(false);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mediaSession.setActive(true);
    }
    return mediaSession;
}
Example 21
Project: Phonograph-master  File: MusicService.java View source code
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);
    mediaSession = new MediaSessionCompat(this, "Phonograph", mediaButtonReceiverComponentName, mediaButtonReceiverPendingIntent);
    mediaSession.setCallback(new MediaSessionCompat.Callback() {

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

        @Override
        public void onPause() {
            pause();
        }

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

        @Override
        public void onSkipToPrevious() {
            back(true);
        }

        @Override
        public void onStop() {
            quit();
        }

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

        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
            return MediaButtonIntentReceiver.handleIntent(MusicService.this, mediaButtonEvent);
        }
    });
    mediaSession.setFlags(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSession.FLAG_HANDLES_MEDIA_BUTTONS);
    mediaSession.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
}
Example 22
Project: quran_android-master  File: AudioService.java View source code
@Override
public void onCreate() {
    Timber.i("debug: Creating service");
    mHandler = new ServiceHandler(this);
    final Context appContext = getApplicationContext();
    mWifiLock = ((WifiManager) appContext.getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "QuranAudioLock");
    mNotificationManager = (NotificationManager) appContext.getSystemService(NOTIFICATION_SERVICE);
    // create the Audio Focus Helper, if the Audio Focus feature is available
    mAudioFocusHelper = new AudioFocusHelper(appContext, this);
    mBroadcastManager = LocalBroadcastManager.getInstance(appContext);
    noisyAudioStreamReceiver = new NoisyAudioStreamReceiver();
    registerReceiver(noisyAudioStreamReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
    ComponentName receiver = new ComponentName(this, MediaButtonReceiver.class);
    mMediaSession = new MediaSessionCompat(appContext, "QuranMediaSession", receiver, null);
    mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mMediaSession.setCallback(new MediaSessionCallback());
    mNotificationColor = ContextCompat.getColor(this, R.color.audio_notification_color);
    try {
        // for Android Wear, use a 1x1 Bitmap with the notification color
        mDisplayIcon = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(mDisplayIcon);
        canvas.drawColor(mNotificationColor);
    } catch (OutOfMemoryError oom) {
        Crashlytics.logException(oom);
    }
}
Example 23
Project: AntennaPod-master  File: PlaybackService.java View source code
@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "Service created.");
    isRunning = true;
    registerReceiver(headsetDisconnected, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
    registerReceiver(shutdownReceiver, new IntentFilter(ACTION_SHUTDOWN_PLAYBACK_SERVICE));
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        registerReceiver(bluetoothStateUpdated, new IntentFilter(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED));
    }
    registerReceiver(audioBecomingNoisy, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
    registerReceiver(skipCurrentEpisodeReceiver, new IntentFilter(ACTION_SKIP_CURRENT_EPISODE));
    registerReceiver(pausePlayCurrentEpisodeReceiver, new IntentFilter(ACTION_PAUSE_PLAY_CURRENT_EPISODE));
    registerReceiver(pauseResumeCurrentEpisodeReceiver, new IntentFilter(ACTION_RESUME_PLAY_CURRENT_EPISODE));
    taskManager = new PlaybackServiceTaskManager(this, taskManagerCallback);
    mediaRouter = MediaRouter.getInstance(getApplicationContext());
    PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(prefListener);
    ComponentName eventReceiver = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(eventReceiver);
    PendingIntent buttonReceiverIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mediaSession = new MediaSessionCompat(getApplicationContext(), TAG, eventReceiver, buttonReceiverIntent);
    try {
        mediaSession.setCallback(sessionCallback);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    } catch (NullPointerException npe) {
        Log.e(TAG, "NullPointerException while setting up MediaSession");
        npe.printStackTrace();
    }
    castManager = CastManager.getInstance();
    castManager.addCastConsumer(castConsumer);
    isCasting = castManager.isConnected();
    if (isCasting) {
        if (UserPreferences.isCastEnabled()) {
            onCastAppConnected(false);
        } else {
            castManager.disconnect();
        }
    } else {
        mediaPlayer = new LocalPSMP(this, mediaPlayerCallback);
    }
    mediaSession.setActive(true);
}
Example 24
Project: TiM-master  File: MusicService.java View source code
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 25
Project: Timber-master  File: MusicService.java View source code
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 26
Project: VCL-Android-master  File: PlaybackService.java View source code
private void initMediaSession(Context context) {
    mSessionCallback = new MediaSessionCallback();
    mMediaSession = new MediaSessionCompat(context, "VLC");
    mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mMediaSession.setCallback(mSessionCallback);
    updateMetadata();
}
Example 27
Project: CastCompanionLibrary-android-master  File: VideoCastManager.java View source code
/*
     * Sets up the {@link MediaSessionCompat} for this application. It also handles the audio
     * focus.
     */
@SuppressLint("InlinedApi")
private void setUpMediaSession(final MediaInfo info) {
    if (!isFeatureEnabled(CastConfiguration.FEATURE_LOCKSCREEN)) {
        return;
    }
    if (mMediaSessionCompat == null) {
        ComponentName mediaEventReceiver = new ComponentName(mContext, VideoIntentReceiver.class.getName());
        mMediaSessionCompat = new MediaSessionCompat(mContext, "TAG", mediaEventReceiver, null);
        mMediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mMediaSessionCompat.setActive(true);
        mMediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {

            @Override
            public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
                KeyEvent keyEvent = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
                if (keyEvent != null && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PAUSE || keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY)) {
                    toggle();
                }
                return true;
            }

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

            @Override
            public void onPause() {
                toggle();
            }

            private void toggle() {
                try {
                    togglePlayback();
                } catch (CastExceptionTransientNetworkDisconnectionException | NoConnectionException |  e) {
                    LOGE(TAG, "MediaSessionCompat.Callback(): Failed to toggle playback", e);
                }
            }
        });
    }
    mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
    PendingIntent pi = getCastControllerPendingIntent();
    if (pi != null) {
        mMediaSessionCompat.setSessionActivity(pi);
    }
    if (info == null) {
        mMediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_NONE, 0, 1.0f).build());
    } else {
        mMediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
    }
    // Update the media session's image
    updateLockScreenImage(info);
    // update the media session's metadata
    updateMediaSessionMetadata();
    mMediaRouter.setMediaSessionCompat(mMediaSessionCompat);
}
Example 28
Project: ListenerMusicPlayer-master  File: MusicService.java View source code
/**
     * �始化和设置MediaSessionCompat
     * MediaSessionCompat用于告诉系统�其他应用当�正在播放的内容,以�接收什么类型的播放控制
     */
private void setUpMediaSession() {
    mSession = new MediaSessionCompat(this, "Listener");
    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 29
Project: shuttle-master  File: VideoCastManager.java View source code
/*
     * Sets up the {@link MediaSessionCompat} for this application. It also handles the audio
     * focus.
     */
@SuppressLint("InlinedApi")
private void setUpMediaSession(final MediaInfo info) {
    if (!isFeatureEnabled(CastConfiguration.FEATURE_LOCKSCREEN)) {
        return;
    }
    if (mMediaSessionCompat == null) {
        ComponentName mediaEventReceiver = new ComponentName(mContext, VideoIntentReceiver.class.getName());
        mMediaSessionCompat = new MediaSessionCompat(mContext, "TAG", mediaEventReceiver, null);
        mMediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mMediaSessionCompat.setActive(true);
        mMediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {

            @Override
            public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
                KeyEvent keyEvent = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
                if (keyEvent != null && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PAUSE || keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY)) {
                    toggle();
                }
                return true;
            }

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

            @Override
            public void onPause() {
                toggle();
            }

            private void toggle() {
                try {
                    togglePlayback();
                } catch (CastExceptionTransientNetworkDisconnectionException | NoConnectionException |  e) {
                    LOGE(TAG, "MediaSessionCompat.Callback(): Failed to toggle playback", e);
                }
            }
        });
    }
    mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
    PendingIntent pi = getCastControllerPendingIntent();
    if (pi != null) {
        mMediaSessionCompat.setSessionActivity(pi);
    }
    if (info == null) {
        mMediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_NONE, 0, 1.0f).build());
    } else {
        mMediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
    }
    // Update the media session's image
    updateLockScreenImage(info);
    // update the media session's metadata
    updateMediaSessionMetadata();
    mMediaRouter.setMediaSessionCompat(mMediaSessionCompat);
}