androidx.media.app.NotificationCompat.MediaStyle Java Examples

The following examples show how to use androidx.media.app.NotificationCompat.MediaStyle. 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: MusicControlModule.java    From react-native-music-control with MIT License 5 votes vote down vote up
private void updateNotificationMediaStyle() {
    if (!Build.MANUFACTURER.toLowerCase(Locale.getDefault()).contains("huawei") && Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        MediaStyle style = new MediaStyle();
        style.setMediaSession(session.getSessionToken());
        int controlCount = 0;
        if(hasControl(PlaybackStateCompat.ACTION_PLAY) || hasControl(PlaybackStateCompat.ACTION_PAUSE) || hasControl(PlaybackStateCompat.ACTION_PLAY_PAUSE)) {
            controlCount += 1;
        }
        if(hasControl(PlaybackStateCompat.ACTION_SKIP_TO_NEXT)) {
            controlCount += 1;
        }
        if(hasControl(PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)) {
            controlCount += 1;
        }
        if(hasControl(PlaybackStateCompat.ACTION_FAST_FORWARD)) {
            controlCount += 1;
        }
        if(hasControl(PlaybackStateCompat.ACTION_REWIND)) {
            controlCount += 1;
        }
        int[] actions = new int[controlCount];
        for(int i=0; i<actions.length; i++) {
            actions[i] = i;
        }
        style.setShowActionsInCompactView(actions);
        nb.setStyle(style);
    }
}
 
Example #2
Source File: PlayerService.java    From Jockey with Apache License 2.0 5 votes vote down vote up
/**
 * Generate and post a notification for the current player status
 * Posts the notification by starting the service in the foreground
 */
private void notifyNowPlaying(boolean foreground) {
    Timber.i("notifyNowPlaying called");

    if (musicPlayer == null || musicPlayer.getMediaSession() == null) {
        Timber.i("Not showing notification. Media session is uninitialized");
        return;
    }

    if (mBeQuiet) {
        mBeQuiet = !musicPlayer.isPlaying();
    }

    NotificationCompat.Builder builder = MediaStyleHelper.from(
            this,
            musicPlayer.getMediaSession(),
            NOTIFICATION_CHANNEL_ID
    );

    setupNotificationActions(builder);

    PendingIntent stopIntent = MediaButtonReceiver.buildMediaButtonPendingIntent(this,
            PlaybackStateCompat.ACTION_STOP);

    builder.setSmallIcon(getNotificationIcon())
            .setDeleteIntent(stopIntent)
            .setStyle(
                    new MediaStyle()
                            .setShowActionsInCompactView(0, 1, 2)
                            .setShowCancelButton(true)
                            .setCancelButtonIntent(stopIntent)
                            .setMediaSession(musicPlayer.getMediaSession().getSessionToken()));

    showNotification(builder.build(), foreground);
}
 
Example #3
Source File: NotificationWrapper.java    From react-native-jw-media-player with MIT License 4 votes vote down vote up
public Notification createNotification(Context context,
                                          MediaSessionCompat mediaSession,
                                          long capabilities
) {
	int appIcon = context.getResources().getIdentifier("ic_app_icon", "drawable", context.getPackageName());

	// Media metadata
	MediaControllerCompat controller = mediaSession.getController();
	MediaMetadataCompat mediaMetadata = controller.getMetadata();
	MediaDescriptionCompat description = mediaMetadata.getDescription();

	// Notification
	NotificationCompat.Builder builder = new NotificationCompat.Builder(context,
																		NOTIFICATION_CHANNEL_ID);
	builder.setContentTitle(description.getTitle())
		   .setContentText(description.getSubtitle())
		   .setSubText(description.getDescription())
		   .setLargeIcon(description.getIconBitmap())
		   .setOnlyAlertOnce(true)
		   .setStyle(new MediaStyle()
				   .setMediaSession(mediaSession.getSessionToken())
				   .setShowActionsInCompactView(0))
		   .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
		   .setSmallIcon(appIcon > 0 ? appIcon : R.drawable.ic_jw_developer)
		   .setDeleteIntent(getActionIntent(context, KeyEvent.KEYCODE_MEDIA_STOP));


	// Attach actions to the notification.
	if ((capabilities & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
		builder.addAction(R.drawable.ic_previous, "Previous",
						  getActionIntent(context,
										  KeyEvent.KEYCODE_MEDIA_PREVIOUS));
	}
	if ((capabilities & PlaybackStateCompat.ACTION_PAUSE) != 0) {
		builder.addAction(R.drawable.ic_pause, "Pause",
						  getActionIntent(context,
										  KeyEvent.KEYCODE_MEDIA_PAUSE));
	}
	if ((capabilities & PlaybackStateCompat.ACTION_PLAY) != 0) {
		builder.addAction(R.drawable.ic_play, "Play",
						  getActionIntent(context,
										  KeyEvent.KEYCODE_MEDIA_PLAY)
		);
	}
	if ((capabilities & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
		builder.addAction(R.drawable.ic_next, "Next",
						  getActionIntent(context,
										  KeyEvent.KEYCODE_MEDIA_NEXT));
	}

	// We want to resume the existing VideoActivity, over creating a new one.
	Intent intent = new Intent(context, context.getClass());
	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
	builder.setContentIntent(pendingIntent);

	Notification notification = builder.build();

	mNotificationManager.notify(NOTIFICATION_ID, notification);

	return notification;
}
 
Example #4
Source File: PlayingNotificationImpl24.java    From Music-Player with GNU General Public License v3.0 4 votes vote down vote up
@Override
public synchronized void update() {
    stopped = false;

    final Song song = service.getCurrentSong();

    final boolean isPlaying = service.isPlaying();
    final boolean isFavorite = MusicUtil.isFavorite(service, song);

    final int playButtonResId = isPlaying
            ? R.drawable.ic_pause_white_24dp : R.drawable.ic_play_arrow_white_24dp;
    final int favButtonResId = isFavorite
            ? R.drawable.ic_favorite_white_24dp : R.drawable.ic_favorite_border_white_24dp;

    Intent action = new Intent(service, MainActivity.class);
    action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    final PendingIntent clickIntent = PendingIntent.getActivity(service, 0, action, 0);

    final ComponentName serviceName = new ComponentName(service, MusicService.class);
    Intent intent = new Intent(MusicService.ACTION_QUIT);
    intent.setComponent(serviceName);
    final PendingIntent deleteIntent = PendingIntent.getService(service, 0, intent, 0);

    final int bigNotificationImageSize = service.getResources().getDimensionPixelSize(R.dimen.notification_big_image_size);
    service.runOnUiThread(() -> SongGlideRequest.Builder.from(Glide.with(service), song)
            .checkIgnoreMediaStore(service)
            .generatePalette(service).build()
            .into(new SimpleTarget<BitmapPaletteWrapper>(bigNotificationImageSize, bigNotificationImageSize) {
                @Override
                public void onResourceReady(BitmapPaletteWrapper resource, GlideAnimation<? super BitmapPaletteWrapper> glideAnimation) {
                    Palette palette = resource.getPalette();
                    update(resource.getBitmap(), palette.getVibrantColor(palette.getMutedColor(Color.TRANSPARENT)));
                }

                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                    update(null, Color.TRANSPARENT);
                }

                void update(Bitmap bitmap, int color) {
                    if (bitmap == null)
                        bitmap = BitmapFactory.decodeResource(service.getResources(), R.drawable.default_album_art);
                    NotificationCompat.Action playPauseAction = new NotificationCompat.Action(playButtonResId,
                            service.getString(R.string.action_play_pause),
                            retrievePlaybackAction(ACTION_TOGGLE_PAUSE));
                    NotificationCompat.Action previousAction = new NotificationCompat.Action(R.drawable.ic_skip_previous_white_24dp,
                            service.getString(R.string.action_previous),
                            retrievePlaybackAction(ACTION_REWIND));
                    NotificationCompat.Action nextAction = new NotificationCompat.Action(R.drawable.ic_skip_next_white_24dp,
                            service.getString(R.string.action_next),
                            retrievePlaybackAction(ACTION_SKIP));
                    NotificationCompat.Action favoriteAction = new NotificationCompat.Action(favButtonResId,
                            service.getString(R.string.action_add_to_favorites),
                            retrievePlaybackAction(ACTION_TOGGLE_FAVORITE));
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(service, NOTIFICATION_CHANNEL_ID)
                            .setSmallIcon(R.drawable.ic_notification)
                            .setLargeIcon(bitmap)
                            .setContentIntent(clickIntent)
                            .setDeleteIntent(deleteIntent)
                            .setContentTitle(song.title)
                            .setContentText(song.artistName)
                            .setOngoing(isPlaying)
                            .setShowWhen(false)
                            .addAction(previousAction)
                            .addAction(playPauseAction)
                            .addAction(nextAction)
                            .addAction(favoriteAction);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        builder.setStyle(new MediaStyle().setMediaSession(service.getMediaSession().getSessionToken()).setShowActionsInCompactView(0, 1, 2))
                                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O && PreferenceUtil.getInstance(service).coloredNotification())
                            builder.setColor(color);
                    }

                    if (stopped)
                        return; // notification has been stopped before loading was finished
                    updateNotifyModeAndPostNotification(builder.build());
                }
            }));
}
 
Example #5
Source File: PlayingNotificationImpl24.java    From MusicPlayer with GNU General Public License v3.0 4 votes vote down vote up
@Override
public synchronized void update() {
    stopped = false;

    final Song song = service.getCurrentSong();

    final boolean isPlaying = service.isPlaying();
    final String text = MusicUtil.getSongInfoString(song);


    Log.d(TAG, "update: isPlaying = "+ isPlaying+", playRes = "+ playButtonResId);
    playButtonResId = isPlaying
            ? R.drawable.ic_pause_white : R.drawable.ic_play_white;

    Intent action = new Intent(service, MainActivity.class);
    action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    action.setAction(ACTION_ON_CLICK_NOTIFICATION);
    final PendingIntent clickIntent = PendingIntent.getActivity(service, 0, action, 0);

    final ComponentName serviceName = new ComponentName(service, MusicService.class);
    Intent intent = new Intent(MusicService.ACTION_QUIT);
    intent.setComponent(serviceName);
    final PendingIntent deleteIntent = PendingIntent.getService(service, 0, intent, 0);

    final int bigNotificationImageSize = service.getResources().getDimensionPixelSize(R.dimen.notification_big_image_size);
    service.runOnUiThread(() ->
            SongGlideRequest.Builder.from(Glide.with(service), song)
            .checkIgnoreMediaStore(service)
            .generatePalette(service).build()
            .into(new SimpleTarget<Bitmap>(bigNotificationImageSize, bigNotificationImageSize) {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    update(resource, Color.TRANSPARENT);
                }

                @Override
                public void onLoadFailed(Drawable errorDrawable) {
                    update(null, Color.TRANSPARENT);
                }

                void update(Bitmap bitmap, int color) {
                    if (bitmap == null)
                        bitmap = BitmapFactory.decodeResource(service.getResources(), R.drawable.default_album_art);

                    Log.d(TAG, "update after glide : playRes = "+ playButtonResId);
                    NotificationCompat.Action playPauseAction = new NotificationCompat.Action(playButtonResId,
                            service.getString(R.string.action_play_pause),
                            retrievePlaybackAction(ACTION_TOGGLE_PAUSE));
                    NotificationCompat.Action previousAction = new NotificationCompat.Action(R.drawable.ic_skip_previous_white_24dp,
                            service.getString(R.string.action_previous),
                            retrievePlaybackAction(ACTION_REWIND));
                    NotificationCompat.Action nextAction = new NotificationCompat.Action(R.drawable.ic_skip_next_white_24dp,
                            service.getString(R.string.action_next),
                            retrievePlaybackAction(ACTION_SKIP));
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(service, NOTIFICATION_CHANNEL_ID)
                            .setSmallIcon(R.drawable.ic_notification)
                            .setLargeIcon(bitmap)
                            .setContentIntent(clickIntent)
                            .setDeleteIntent(deleteIntent)
                            .setContentTitle(song.title)
                            .setContentText(text)
                            .setOngoing(isPlaying)
                            .setShowWhen(false)
                            .addAction(previousAction)
                            .addAction(playPauseAction)
                            .addAction(nextAction);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        builder.setStyle(new MediaStyle().setMediaSession(service.getMediaSession().getSessionToken()).setShowActionsInCompactView(0, 1, 2))
                                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O && PreferenceUtil.getInstance(service).coloredNotification())
                            builder.setColor(color);
                    }

                    if (stopped)
                        return; // notification has been stopped before loading was finished
                    updateNotifyModeAndPostNotification(builder.build());
                }
            }));
}
 
Example #6
Source File: SteamService.java    From UpdogFarmer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Show idling notification
 * @param game
 */
private void showIdleNotification(Game game) {
    Log.i(TAG, "Idle notification");
    final Intent notificationIntent = new Intent(this, MainActivity.class);
    final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.now_playing2,
                    (game.appId == 0) ? getString(R.string.playing_non_steam_game, game.name) : game.name))
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentIntent(pendingIntent);

    // MediaStyle causes a crash on certain Huawei devices running Lollipop
    // https://stackoverflow.com/questions/34851943/couldnt-expand-remoteviews-mediasessioncompat-and-notificationcompat-mediastyl
    if (!isHuawei) {
        builder.setStyle(new MediaStyle());
    }

    if (game.dropsRemaining > 0) {
        // Show drops remaining
        builder.setSubText(getResources().getQuantityString(R.plurals.card_drops_remaining, game.dropsRemaining, game.dropsRemaining));
    }

    // Add the stop and pause actions
    final PendingIntent stopIntent = PendingIntent.getBroadcast(this, 0, new Intent(STOP_INTENT), PendingIntent.FLAG_CANCEL_CURRENT);
    final PendingIntent pauseIntent = PendingIntent.getBroadcast(this, 0, new Intent(PAUSE_INTENT), PendingIntent.FLAG_CANCEL_CURRENT);
    builder.addAction(R.drawable.ic_action_stop, getString(R.string.stop), stopIntent);
    builder.addAction(R.drawable.ic_action_pause, getString(R.string.pause), pauseIntent);

    if (farming) {
        // Add the skip action
        final PendingIntent skipIntent = PendingIntent.getBroadcast(this, 0, new Intent(SKIP_INTENT), PendingIntent.FLAG_CANCEL_CURRENT);
        builder.addAction(R.drawable.ic_action_skip, getString(R.string.skip), skipIntent);
    }

    final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (!PrefsManager.minimizeData()) {
        // Load game icon into notification
        Glide.with(getApplicationContext())
                .load(game.iconUrl)
                .asBitmap()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        builder.setLargeIcon(resource);
                        nm.notify(NOTIF_ID, builder.build());
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        nm.notify(NOTIF_ID, builder.build());
                    }
                });
    } else {
        nm.notify(NOTIF_ID, builder.build());
    }
}
 
Example #7
Source File: PlayingNotificationImpl24.java    From VinylMusicPlayer with GNU General Public License v3.0 4 votes vote down vote up
@Override
public synchronized void update() {
    stopped = false;

    final Song song = service.getCurrentSong();

    final boolean isPlaying = service.isPlaying();
    final boolean isFavorite = MusicUtil.isFavorite(service, song);
    final String text = MusicUtil.getSongInfoString(song);

    final int playButtonResId = isPlaying
            ? R.drawable.ic_pause_white_24dp : R.drawable.ic_play_arrow_white_24dp;
    final int favButtonResId = isFavorite ? R.drawable.ic_favorite_white_24dp : R.drawable.ic_favorite_border_white_24dp;

    Intent action = new Intent(service, MainActivity.class);
    action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    final PendingIntent clickIntent = PendingIntent.getActivity(service, 0, action, 0);

    final ComponentName serviceName = new ComponentName(service, MusicService.class);
    Intent intent = new Intent(MusicService.ACTION_QUIT);
    intent.setComponent(serviceName);
    final PendingIntent deleteIntent = PendingIntent.getService(service, 0, intent, 0);

    final int bigNotificationImageSize = service.getResources().getDimensionPixelSize(R.dimen.notification_big_image_size);
    service.runOnUiThread(() -> GlideApp.with(service)
            .asBitmapPalette()
            .load(VinylGlideExtension.getSongModel(song))
            .transition(VinylGlideExtension.getDefaultTransition())
            .songOptions(song)
            .into(new VinylSimpleTarget<BitmapPaletteWrapper>(bigNotificationImageSize, bigNotificationImageSize) {
                @Override
                public void onResourceReady(@NonNull BitmapPaletteWrapper resource, Transition<? super BitmapPaletteWrapper> glideAnimation) {
                    Palette palette = resource.getPalette();
                    update(resource.getBitmap(), palette.getVibrantColor(palette.getMutedColor(Color.TRANSPARENT)));
                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                    update(null, Color.TRANSPARENT);
                }

                void update(Bitmap bitmap, int color) {
                    if (bitmap == null)
                        bitmap = BitmapFactory.decodeResource(service.getResources(), R.drawable.default_album_art);
                    NotificationCompat.Action playPauseAction = new NotificationCompat.Action(playButtonResId,
                            service.getString(R.string.action_play_pause),
                            retrievePlaybackAction(ACTION_TOGGLE_PAUSE));
                    NotificationCompat.Action previousAction = new NotificationCompat.Action(R.drawable.ic_skip_previous_white_24dp,
                            service.getString(R.string.action_previous),
                            retrievePlaybackAction(ACTION_REWIND));
                    NotificationCompat.Action nextAction = new NotificationCompat.Action(R.drawable.ic_skip_next_white_24dp,
                            service.getString(R.string.action_next),
                            retrievePlaybackAction(ACTION_SKIP));
                    NotificationCompat.Action favoriteAction = new NotificationCompat.Action(favButtonResId,
                            service.getString(R.string.action_toggle_favorite),
                            retrievePlaybackAction(TOGGLE_FAVORITE));
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(service, NOTIFICATION_CHANNEL_ID)
                            .setSmallIcon(R.drawable.ic_notification)
                            .setLargeIcon(bitmap)
                            .setContentIntent(clickIntent)
                            .setDeleteIntent(deleteIntent)
                            .setContentTitle(song.title)
                            .setContentText(text)
                            .setOngoing(isPlaying)
                            .setShowWhen(false)
                            .addAction(previousAction)
                            .addAction(playPauseAction)
                            .addAction(nextAction)
                            .addAction(favoriteAction);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        builder.setStyle(new MediaStyle().setMediaSession(service.getMediaSession().getSessionToken()).setShowActionsInCompactView(0, 1, 2))
                                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O && PreferenceUtil.getInstance().coloredNotification())
                            builder.setColor(color);
                    }

                    if (stopped)
                        return; // notification has been stopped before loading was finished
                    updateNotifyModeAndPostNotification(builder.build());
                }
            }));
}
 
Example #8
Source File: BackgroundAudioService.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
/**
     * Builds notification panel with buttons and info on it
     *
     * @param action Action to be applied
     */

    private void buildNotification(NotificationCompat.Action action)
    {
        final MediaStyle style = new MediaStyle();

        Intent intent = new Intent(getApplicationContext(), BackgroundAudioService.class);
        intent.setAction(ACTION_STOP);
        PendingIntent stopPendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);

        Intent clickIntent = new Intent(this, MainActivity.class);
        clickIntent.setAction(Intent.ACTION_MAIN);
        clickIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent clickPendingIntent = PendingIntent.getActivity(this, 0, clickIntent, 0);

        notificationBuilder = new NotificationCompat.Builder(this);
        notificationBuilder.setSmallIcon(R.drawable.ic_notification);
        notificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        notificationBuilder.setContentTitle(currentVideo.getTitle());
        notificationBuilder.setContentInfo(currentVideo.getDuration());
        notificationBuilder.setUsesChronometer(true);
        notificationBuilder.setContentIntent(clickPendingIntent);
        notificationBuilder.setDeleteIntent(stopPendingIntent);
//        notificationBuilder.setOngoing(true);
        notificationBuilder.setSubText(Utils.formatViewCount(currentVideo.getViewCount()));
        notificationBuilder.setStyle(style);

        //load bitmap for largeScreen
        if (currentVideo.getThumbnailURL() != null && !currentVideo.getThumbnailURL().isEmpty()) {
            Picasso.with(this)
                    .load(currentVideo.getThumbnailURL())
                    .resize(Config.MAX_WIDTH_ICON, Config.MAX_HEIGHT_ICON)
                    .centerCrop()
                    .into(target);
        }

        notificationBuilder.addAction(generateIntentAction(ACTION_PREVIOUS));
        notificationBuilder.addAction(generateIntentAction(ACTION_NEXT));
//        notificationBuilder.updateAction(generateAction(
//                R.drawable.ic_skip_previous_white_24dp,
//                getApplicationContext().getString(R.string.action_previous),
//                ACTION_PREVIOUS
//        ));
//        notificationBuilder.updateAction(generateAction(
//                R.drawable.ic_skip_next_white_24dp,
//                getApplicationContext().getString(R.string.action_next),
//                CUSTOM_ACTION_NEXT));
        notificationBuilder.addAction(action);
        LogHelper.e(TAG, "setNotificationPlaybackState. mediaPlayer=" + mediaPlayer);
        setNotificationPlaybackState(notificationBuilder);

        style.setShowActionsInCompactView(0, 1, 2);

        NotificationManager notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
    }
 
Example #9
Source File: NotificationBuilder.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
public Notification buildNotification(MediaSessionCompat.Token sessionToken) throws RemoteException
{
    if (shouldCreateNowRunningChannel()) {
        createNotificationChannel();
    }
    mediaController = new MediaControllerCompat(context, sessionToken);
    MediaMetadataCompat metadata = mediaController.getMetadata();
    mediaDescription = metadata.getDescription();
    playbackState = mediaController.getPlaybackState();

    builder = new NotificationCompat.Builder(context, CHANNEL_ID);

    // Only add actions for skip back, play/pause, skip forward, based on what's enabled.
    int playPauseIndex = 0;
    if (isSkipToPreviousEnabled()) {
        builder.addAction(skipToPreviousAction);
        playPauseIndex++;
    }

    if (isPlaying()) {
        builder.addAction(pauseAction);
    } else if (isPlayEnabled()) {
        builder.addAction(playAction);
    }

    if (isSkipToNextEnabled()) {
        builder.addAction(skipToNextAction);
    }

    MediaStyle mediaStyle = new MediaStyle()
            .setCancelButtonIntent(stopPendingIntent)
            .setMediaSession(sessionToken)
            .setShowActionsInCompactView(playPauseIndex)
            .setShowCancelButton(true);

    return builder.setContentIntent(mediaController.getSessionActivity())
            .setContentText(mediaDescription.getSubtitle())
            .setContentTitle(mediaDescription.getTitle())
            .setDeleteIntent(stopPendingIntent)
            .setLargeIcon(mediaDescription.getIconBitmap())
            .setOnlyAlertOnce(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setStyle(mediaStyle)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .build();
}
 
Example #10
Source File: MediaNotificationManager.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
public Notification buildNotification(MediaSessionCompat.Token sessionToken)
{
    LogHelper.d(TAG, "updateNotificationMetadata. currentYouTubeVideo=" + currentYouTubeVideo);
    if (currentYouTubeVideo == null || playbackState == null) return null;

    if (shouldCreateNowRunningChannel()) {
        createNotificationChannel();
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);

    // Only add actions for skip back, play/pause, skip forward, based on what's enabled.
    int playPauseIndex = 0;
    if (isSkipToPreviousEnabled()) {
        builder.addAction(skipToPreviousAction);
        playPauseIndex++;
    }

    if (isPlaying()) {
        builder.addAction(pauseAction);
    } else if (isPlayEnabled()) {
        builder.addAction(playAction);
    }

    if (isSkipToNextEnabled()) {
        builder.addAction(skipToNextAction);
    }

    MediaStyle mediaStyle = new MediaStyle()
            .setMediaSession(sessionToken)
            .setShowActionsInCompactView(playPauseIndex)
            .setShowCancelButton(true)
            .setCancelButtonIntent(stopPendingIntent);

    builder.setContentIntent(mediaController.getSessionActivity())
            .setContentTitle(currentYouTubeVideo.getTitle())
            .setContentInfo(currentYouTubeVideo.getDuration())
            .setSubText(Utils.formatViewCount(currentYouTubeVideo.getViewCount()))
            .setContentIntent(clickPendingIntent)
            .setDeleteIntent(stopPendingIntent)
            .setOnlyAlertOnce(true)
            .setUsesChronometer(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setStyle(mediaStyle)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);


    if (isPlaying() && playbackState.getPosition() > 0) {
        builder
                .setWhen(System.currentTimeMillis() - playbackState.getPosition())
                .setShowWhen(true)
                .setUsesChronometer(true);
    } else {
        builder
                .setWhen(0)
                .setShowWhen(false)
                .setUsesChronometer(false);
    }

    // Load bitmap
    if (currentYouTubeVideo.getThumbnailURL() != null && !currentYouTubeVideo.getThumbnailURL().isEmpty()) {
        target.setNotificationBuilder(builder);
        Picasso.with(exoAudioService)
                .load(currentYouTubeVideo.getThumbnailURL())
                .resize(Config.MAX_WIDTH_ICON, Config.MAX_HEIGHT_ICON)
                .centerCrop()
                .into(target);
    }

    return builder.build();
}
 
Example #11
Source File: MediaNotificationManager.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
private Notification createNotification()
    {
        LogHelper.d(TAG, "updateNotificationMetadata. currentYouTubeVideo=" + currentYouTubeVideo);
        if (currentYouTubeVideo == null || playbackState == null) {
            return null;
        }

        Intent clickIntent = new Intent(exoAudioService, MainActivity.class);
        clickIntent.setAction(Intent.ACTION_MAIN);
        clickIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent clickPendingIntent = PendingIntent.getActivity(exoAudioService, 0, clickIntent, 0);

        // Notification channels are only supported on Android O+.
        if (shouldCreateNowRunningChannel()) {
            createNotificationChannel();
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(exoAudioService, CHANNEL_ID);
        int playPauseButtonPosition = 0;

        // If skip to previous action is enabled
        if ((playbackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
            notificationBuilder.addAction(
                    R.drawable.ic_skip_previous_white_24dp,
                    exoAudioService.getString(R.string.action_previous), previousIntent
            );

            // If there is a "skip to previous" button, the play/pause button will
            // be the second one. We need to keep track of it, because the MediaStyle notification
            // requires to specify the index of the buttons (actions) that should be visible
            // when in compact view.
            playPauseButtonPosition = 1;
        }

        addPlayPauseAction(notificationBuilder);

        // If skip to next action is enabled
        if ((playbackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
            notificationBuilder.addAction(
                    R.drawable.ic_skip_next_white_24dp,
                    exoAudioService.getString(R.string.action_next),
                    nextIntent
            );
        }

        // show only play/pause in compact view
        MediaStyle mediaStyle = new MediaStyle()
                .setCancelButtonIntent(stopPendingIntent)
                .setMediaSession(sessionToken)
                .setShowActionsInCompactView(playPauseButtonPosition)
                .setShowCancelButton(true);

        notificationBuilder
                .setStyle(mediaStyle)
//                .setColor(mNotificationColor)
                .setSmallIcon(R.drawable.ic_notification)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentTitle(currentYouTubeVideo.getTitle())
                .setContentInfo(currentYouTubeVideo.getDuration())
                .setDeleteIntent(stopPendingIntent)
                .setUsesChronometer(true)
                .setOnlyAlertOnce(true)
                .setContentIntent(clickPendingIntent)
                .setSubText(Utils.formatViewCount(currentYouTubeVideo.getViewCount()));

        setNotificationPlaybackState(notificationBuilder);

        //load bitmap
        if (currentYouTubeVideo.getThumbnailURL() != null && !currentYouTubeVideo.getThumbnailURL().isEmpty()) {
            target.setNotificationBuilder(notificationBuilder);
            Picasso.with(exoAudioService)
                    .load(currentYouTubeVideo.getThumbnailURL())
                    .resize(Config.MAX_WIDTH_ICON, Config.MAX_HEIGHT_ICON)
                    .centerCrop()
                    .into(target);
        }
        return notificationBuilder.build();
    }
 
Example #12
Source File: MusicControlModule.java    From react-native-music-control with MIT License 4 votes vote down vote up
@ReactMethod
synchronized public void setNowPlaying(ReadableMap metadata) {
    init();
    if(artworkThread != null && artworkThread.isAlive()) artworkThread.interrupt();

    String title = metadata.hasKey("title") ? metadata.getString("title") : null;
    String artist = metadata.hasKey("artist") ? metadata.getString("artist") : null;
    String album = metadata.hasKey("album") ? metadata.getString("album") : null;
    String genre = metadata.hasKey("genre") ? metadata.getString("genre") : null;
    String description = metadata.hasKey("description") ? metadata.getString("description") : null;
    String date = metadata.hasKey("date") ? metadata.getString("date") : null;
    long duration = metadata.hasKey("duration") ? (long)(metadata.getDouble("duration") * 1000) : 0;
    int notificationColor = metadata.hasKey("color") ? metadata.getInt("color") : NotificationCompat.COLOR_DEFAULT;
    String notificationIcon = metadata.hasKey("notificationIcon") ? metadata.getString("notificationIcon") : null;

    // If a color is supplied, we need to clear the MediaStyle set during init().
    // Otherwise, the color will not be used for the notification's background.
    boolean removeFade = metadata.hasKey("color");
    if(removeFade) {
        nb.setStyle(new MediaStyle());
    }

    RatingCompat rating;
    if(metadata.hasKey("rating")) {
        if(ratingType == RatingCompat.RATING_PERCENTAGE) {
            rating = RatingCompat.newPercentageRating((float)metadata.getDouble("rating"));
        } else if(ratingType == RatingCompat.RATING_HEART) {
            rating = RatingCompat.newHeartRating(metadata.getBoolean("rating"));
        } else if(ratingType == RatingCompat.RATING_THUMB_UP_DOWN) {
            rating = RatingCompat.newThumbRating(metadata.getBoolean("rating"));
        } else {
            rating = RatingCompat.newStarRating(ratingType, (float)metadata.getDouble("rating"));
        }
    } else {
        rating = RatingCompat.newUnratedRating(ratingType);
    }

    md.putText(MediaMetadataCompat.METADATA_KEY_TITLE, title);
    md.putText(MediaMetadataCompat.METADATA_KEY_ARTIST, artist);
    md.putText(MediaMetadataCompat.METADATA_KEY_ALBUM, album);
    md.putText(MediaMetadataCompat.METADATA_KEY_GENRE, genre);
    md.putText(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, description);
    md.putText(MediaMetadataCompat.METADATA_KEY_DATE, date);
    md.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration);
    if (android.os.Build.VERSION.SDK_INT > 19) {
        md.putRating(MediaMetadataCompat.METADATA_KEY_RATING, rating);
    }

    nb.setContentTitle(title);
    nb.setContentText(artist);
    nb.setContentInfo(album);
    nb.setColor(notificationColor);

    notification.setCustomNotificationIcon(notificationIcon);

    if(metadata.hasKey("artwork")) {
        String artwork = null;
        boolean localArtwork = false;

        if(metadata.getType("artwork") == ReadableType.Map) {
            artwork = metadata.getMap("artwork").getString("uri");
            localArtwork = true;
        } else {
            artwork = metadata.getString("artwork");
        }

        final String artworkUrl = artwork;
        final boolean artworkLocal = localArtwork;

        artworkThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = loadArtwork(artworkUrl, artworkLocal);

                if(md != null) {
                    md.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, bitmap);
                    session.setMetadata(md.build());
                }
                if(nb != null) {
                    nb.setLargeIcon(bitmap);
                    notification.show(nb, isPlaying);
                }

                artworkThread = null;
            }
        });
        artworkThread.start();
    } else {
        md.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, null);
        nb.setLargeIcon(null);
    }

    session.setMetadata(md.build());
    session.setActive(true);
    notification.show(nb, isPlaying);
}
 
Example #13
Source File: MediaNotificationManager.java    From klingar with Apache License 2.0 4 votes vote down vote up
private Notification createNotification() {
  Timber.d("createNotification currentTrack %s", currentTrack);
  if (currentTrack == null) {
    return null;
  }

  // Notification channels are only supported on Android O+.
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    createNotificationChannel();
  }

  NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(service,
      CHANNEL_ID);

  notificationBuilder.addAction(R.drawable.ic_notification_previous,
      service.getString(R.string.label_previous), previousIntent);

  addPlayPauseAction(notificationBuilder);

  notificationBuilder.addAction(R.drawable.ic_notification_next,
      service.getString(R.string.label_next), nextIntent);

  notificationBuilder
      .setStyle(new MediaStyle()
          .setShowActionsInCompactView(1) // show only play/pause in compact view
          .setShowCancelButton(true)
          .setCancelButtonIntent(stopCastIntent)
          .setMediaSession(musicController.getSessionToken()))
      .setDeleteIntent(stopCastIntent)
      .setColor(notificationColor)
      .setSmallIcon(R.drawable.ic_notification)
      .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
      .setOnlyAlertOnce(true)
      .setContentIntent(createContentIntent())
      .setContentTitle(currentTrack.title())
      .setContentText(currentTrack.artistTitle());

  String castName = musicController.getCastName();
  if (castName != null) {
    String castInfo = service.getResources().getString(R.string.casting_to_device, castName);
    notificationBuilder.setSubText(castInfo);
    notificationBuilder.addAction(R.drawable.ic_notification_close,
        service.getString(R.string.stop_casting), stopCastIntent);
  }

  setNotificationPlaybackState(notificationBuilder);

  if (currentTrack.thumb() != null) {
    loadImage(currentTrack.thumb(), notificationBuilder);
  }

  return notificationBuilder.build();
}
 
Example #14
Source File: PlayingNotificationImpl24.java    From Phonograph with GNU General Public License v3.0 4 votes vote down vote up
@Override
public synchronized void update() {
    stopped = false;

    final Song song = service.getCurrentSong();

    final boolean isPlaying = service.isPlaying();

    final int playButtonResId = isPlaying
            ? R.drawable.ic_pause_white_24dp : R.drawable.ic_play_arrow_white_24dp;

    Intent action = new Intent(service, MainActivity.class);
    action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    final PendingIntent clickIntent = PendingIntent.getActivity(service, 0, action, 0);

    final ComponentName serviceName = new ComponentName(service, MusicService.class);
    Intent intent = new Intent(MusicService.ACTION_QUIT);
    intent.setComponent(serviceName);
    final PendingIntent deleteIntent = PendingIntent.getService(service, 0, intent, 0);

    final int bigNotificationImageSize = service.getResources().getDimensionPixelSize(R.dimen.notification_big_image_size);
    service.runOnUiThread(() -> SongGlideRequest.Builder.from(Glide.with(service), song)
            .checkIgnoreMediaStore(service)
            .generatePalette(service).build()
            .into(new SimpleTarget<BitmapPaletteWrapper>(bigNotificationImageSize, bigNotificationImageSize) {
                @Override
                public void onResourceReady(BitmapPaletteWrapper resource, GlideAnimation<? super BitmapPaletteWrapper> glideAnimation) {
                    Palette palette = resource.getPalette();
                    update(resource.getBitmap(), palette.getVibrantColor(palette.getMutedColor(Color.TRANSPARENT)));
                }

                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                    update(null, Color.TRANSPARENT);
                }

                void update(Bitmap bitmap, int color) {
                    if (bitmap == null)
                        bitmap = BitmapFactory.decodeResource(service.getResources(), R.drawable.default_album_art);
                    NotificationCompat.Action playPauseAction = new NotificationCompat.Action(playButtonResId,
                            service.getString(R.string.action_play_pause),
                            retrievePlaybackAction(ACTION_TOGGLE_PAUSE));
                    NotificationCompat.Action previousAction = new NotificationCompat.Action(R.drawable.ic_skip_previous_white_24dp,
                            service.getString(R.string.action_previous),
                            retrievePlaybackAction(ACTION_REWIND));
                    NotificationCompat.Action nextAction = new NotificationCompat.Action(R.drawable.ic_skip_next_white_24dp,
                            service.getString(R.string.action_next),
                            retrievePlaybackAction(ACTION_SKIP));
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(service, NOTIFICATION_CHANNEL_ID)
                            .setSmallIcon(R.drawable.ic_notification)
                            .setSubText(song.albumName)
                            .setLargeIcon(bitmap)
                            .setContentIntent(clickIntent)
                            .setDeleteIntent(deleteIntent)
                            .setContentTitle(song.title)
                            .setContentText(song.artistName)
                            .setOngoing(isPlaying)
                            .setShowWhen(false)
                            .addAction(previousAction)
                            .addAction(playPauseAction)
                            .addAction(nextAction);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        builder.setStyle(new MediaStyle().setMediaSession(service.getMediaSession().getSessionToken()).setShowActionsInCompactView(0, 1, 2))
                                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O && PreferenceUtil.getInstance(service).coloredNotification())
                            builder.setColor(color);
                    }

                    if (stopped)
                        return; // notification has been stopped before loading was finished
                    updateNotifyModeAndPostNotification(builder.build());
                }
            }));
}