web-dev-qa-db-fra.com

Comment ajouter un bouton aux notifications dans Android?

Mon application lit de la musique et lorsque les utilisateurs ouvrent l'écran des notifications en glissant depuis le haut de l'écran (ou généralement en bas à droite de l'écran sur des tablettes), je souhaite leur présenter un bouton pour arrêter la musique en cours de lecture et la redémarrer si Ils veulent.

Je ne prévois pas de placer un widget sur l'écran d'accueil de l'utilisateur, mais simplement dans les notifications. Comment puis-je faire ceci?

68
frankish

Ajouter un bouton d'action à la notification

Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);

NotificationCompat.Builder mBuilder = new 
NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent);

Pour plus de détails, visitez https://developer.Android.com/training/notify-user/build-notification.html

5
labhya sharma
    // It shows buttons on lock screen (notification).

Notification notification = new Notification.Builder(context)
    .setVisibility(Notification.VISIBILITY_PUBLIC)
    .setSmallIcon(R.drawable.NotIcon)
    .addAction(R.drawable.ic_prev, "button1",ButtonOneScreen) 
    .addAction(R.drawable.ic_pause, "button2", ButtonTwoScreen)  
   .....
    .setStyle(new Notification.MediaStyle()
    .setShowActionsInCompactView(1)
    .setMediaSession(mMediaSession.getSessionToken())
    .setContentTitle("your choice")
    .setContentText("Again your choice")
    .setLargeIcon(buttonIcon)
    .build();

Veuillez vous référer à ceci pour plus de détails Cliquez ici

3
Chandsi Gupta

Vous pouvez créer une intention pour l'action (dans ce cas, arrêtez de jouer) et ajoutez-la en tant que bouton d'action à votre notification.

Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent);

Veuillez vous référer à la documentation Android ici

3
Ruben Miquelino

testé, code de travail avec Android Pie. Ceux-ci vont tous dans la même classe de service.

Afficher une notification:

public void setNotification() {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
    NotificationChannel channel = new NotificationChannel("a", "status", NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("notifications");
    notificationManager = getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(channel);

    }
else
    notificationManager =  (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


Receiver.service = this;
Notification.MediaStyle style = new Notification.MediaStyle();

notification = new Notification.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("Notification")
        .addAction(R.drawable.close_icon,  "quit_action", makePendingIntent("quit_action"))
        .setStyle(style);

style.setShowActionsInCompactView(0);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
    notification.setChannelId("a");
    }

// notificationManager.notify(123 , notification.build()); // pre-oreo
startForeground(126, notification.getNotification());
}

Fonction d'assistance:

public PendingIntent makePendingIntent(String name)
    {
    Intent intent = new Intent(this, FloatingViewService.Receiver.class);
    intent.setAction(name);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    return pendingIntent;
    }

Pour gérer les actions:

static public class Receiver extends BroadcastReceiver {
static FloatingViewService service;

@Override
public void onReceive(Context context, Intent intent)
    {

    String whichAction = intent.getAction();

    switch (whichAction)
        {

        case "quit_action":
            service.stopForeground(true);
            service.stopSelf();
            return;

        }

    }
}

Vous devrez également mettre à jour votre manifeste:

<receiver Android:name=".FloatingViewService$Receiver">
        <intent-filter>
            <action Android:name="quit_action" />
        </intent-filter>
    </receiver>
1
Al Ro

Je pense qu’à côté de Ankit Gupta réponse, vous pouvez utiliser MediaSession (API> 21) pour ajouter un message natif mediaController :

notificationBuilder
        .setStyle(new Notification.MediaStyle()
            .setShowActionsInCompactView(new int[]{playPauseButtonPosition})  // show only play/pause in compact view
            .setMediaSession(mSessionToken))
        .setColor(mNotificationColor)
        .setSmallIcon(R.drawable.ic_notification)
        .setVisibility(Notification.VISIBILITY_PUBLIC)
        .setUsesChronometer(true)
        .setContentIntent(createContentIntent(description)) // Create an intent that would open the UI when user clicks the notification
        .setContentTitle(description.getTitle())
        .setContentText(description.getSubtitle())
        .setLargeIcon(art);

Source: tutoriel

vous pouvez également créer une vue personnalisée et l'afficher dans la zone de notification, première réponse: ici c'est bien.

1
tabebqena

Je vais essayer de fournir une solution que j'ai utilisée et la plupart des lecteurs de musique utilisent également la même technique pour afficher les contrôles du lecteur dans la barre de notification. 

J'utilise un service permettant de gérer Media Player et tous ses contrôles. Le contrôle d'activité d'utilisateur interagit avec le service en envoyant par exemple des intentions au service

 Intent i = new Intent(MainActivity.this, MyRadioService.class);
        i.setAction(Constants.Player.ACTION_PAUSE);

        startService(i);

POUR recevoir des intentions et effectuer des actions dans la classe Service, j'utilise le code suivant dans la méthode onStartCommand de Service

 @Override
public int onStartCommand(Intent intent, int flags, int startId) {


    if (intent.getAction().equals(Constants.Player.ACTION_PAUSE)) {
        if(mediaPlayer.isPlaying()) {
            pauseAudio();
        }
    }

Maintenant, pour répondre exactement à votre question, affichez la notification avec les commandes à jouer. Vous pouvez appeler les méthodes suivantes pour afficher une notification avec des contrôles.

   //    showNotification
private void startAppInForeground() {
//  Start Service in Foreground

    // Using RemoteViews to bind custom layouts into Notification
    RemoteViews views = new RemoteViews(getPackageName(),
            R.layout.notification_status_bar);

// Define play control intent 
   Intent playIntent = new Intent(this, MyRadioService.class);
    playIntent.setAction(Constants.Player.ACTION_PLAY);

// Use the above play intent to set into PendingIntent
    PendingIntent pplayIntent = PendingIntent.getService(this, 0,
            playIntent, 0);

// binding play button from layout to pending play intent defined above 
views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent);
views.setImageViewResource(R.id.status_bar_play,
            R.drawable.status_bg);

Notification status = null;
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        status = new Notification.Builder(this).build();
    }

  status.flags = Notification.FLAG_ONGOING_EVENT;
    status.icon = R.mipmap.ic_launcher;
    status.contentIntent = pendingIntent;
    startForeground(Constants.FOREGROUND_SERVICE, status);

} J'espère que cela vous aide vraiment. Et vous pourrez réaliser ce que vous voulez. Bonne codage :) 

0
Ankit Gupta