Hoe voeg ik een knop toe aan meldingen in Android?

Mijn app speelt muziek af en wanneer gebruikers het meldingsscherm openen door vanaf de bovenkant van het scherm te vegen (of in het algemeen vanaf de rechterbenedenhoek van het scherm op tablets), wil ik ze een knop presenteren om de momenteel afgespeelde muziek te stoppen en te starten het opnieuw als ze willen.

Ik ben niet van plan om een ​​widget op het startscherm van de gebruiker te plaatsen, maar alleen in meldingen. Hoe kan ik dit doen?


Antwoord 1, autoriteit 100%

Je kunt een intentie voor de actie maken (in dit geval stoppen met spelen) en deze vervolgens als actieknop aan je melding toevoegen.

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);

Raadpleeg de Android-documentatie.


Antwoord 2, autoriteit 33%

Ik zal proberen een oplossing te bieden die ik heb gebruikt en de meeste muziekspelers gebruiken dezelfde techniek ook om spelerbedieningen in de meldingsbalk weer te geven.

Ik gebruik een service die wordt gebruikt om Media Player en al zijn bedieningselementen te beheren. Activiteit Gebruikersbeheer werkt samen met de service door bijvoorbeeld intenties naar de service te sturen

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

Om intenties te ontvangen en actie uit te voeren in de serviceklasse, gebruik ik de volgende code in de onStartCommand-servicemethode

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent.getAction().equals(Constants.Player.ACTION_PAUSE)) {
        if(mediaPlayer.isPlaying()) {
            pauseAudio();
        }
    }

Nu het exacte antwoord op je vraag om een ​​melding weer te geven met afspeelbesturing. U kunt de volgende methoden aanroepen om meldingen met bedieningselementen weer te geven.

  //    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);

}
Hoop dat dit je echt helpt. En je zult in staat zijn om te bereiken wat je wilt. Veel plezier met coderen 🙂


Antwoord 3, autoriteit 33%

   // 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();

Zie dit voor meer details Klik hier


4, Autoriteit 20%

Getest, Werkcode met Android Pie. Deze gaan allemaal in dezelfde serviceklasse.

Toon een melding:

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());
}

Helperfunctie:

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;
    }

om de acties af te handelen:

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;
        }
    }
}

U moet ook uw manifest bijwerken:

<receiver android:name=".FloatingViewService$Receiver">
        <intent-filter>
            <action android:name="quit_action" />
        </intent-filter>
    </receiver>

Antwoord 5, autoriteit 7%

u kunt een knop toevoegen zoals hieronder en actie uitvoeren op die knop, ook heb ik voor mij gedaan zoals hieronder, controleer dit alstublieft.

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_logo)
                        .setAutoCancel(true)
                        .setContentTitle(name)
                        .setContentText(body)
                        .setGroupSummary(true)
                        .addAction(android.R.drawable.ic_menu_directions, "Mark as read", morePendingIntent);

//morePendingIntent(doe je ding)

 PendingIntent morePendingIntent = PendingIntent.getBroadcast(
                        this,
                        REQUEST_CODE_MORE,
                        new Intent(this, NotificationReceiver.class)
                                .putExtra(KEY_INTENT_MORE, REQUEST_CODE_MORE)
                                .putExtra("bundle", object.toString()),
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

Antwoord 6

Ik weet niet of dit de juiste manier is of niet, maar het werkt.

  1. Maak een BroadCastReceiver-klasse om de gegevens te ontvangen wanneer op de knop wordt gedrukt.
public class MyBroadCastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String log = "URI: " + intent.toUri(Intent.URI_INTENT_SCHEME);
        Log.d("my", "LOG:::::::" + log);
    }
}
  1. Nu in elke activiteit waar u de melding wilt maken –
Intent intent = new Intent();
        intent.setAction("unique_id");
        intent.putExtra("key", "any data you want to send when button is pressed");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0);
  1. Gebruik nu deze lopende intentie wanneer u de melding maakt en tot slot moet u deze uitzending registreren om deze te ontvangen in de MyBroadCastReceiver-klasse.
BroadcastReceiver br = new MyBroadCastReceiver();
        IntentFilter filter = new IntentFilter("unique_id");
        registerReceiver(br, filter);

Als u nu bepaalde dingen wilt doen wanneer de knop wordt ingedrukt, kunt u dat doen met de onReceive()-methode in de klasse MyBroadCastReceiver.

Other episodes