Action buttons are not shown in notification

2019-08-06 03:03发布

问题:

I want to display action buttons in notification bar. Notification works but I cannot see any button . I have read Android Developer document and different examples on the Internet but I could not find any big difference with my code. I have done like following:

public void showNotification(Context context) {
    NotificationManager mNotifyMgr = (NotificationManager);     
    context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder = new NotificationCompat.Builder(context);

    Intent prevIntent = new Intent(mContext, PlayAudioService.class);
    prevIntent.setAction(ACTION_PREV);
    PendingIntent piPrev = PendingIntent.getService(mContext, 0, prevIntent, 0);

    Intent playIntent = new Intent(mContext, PlayAudioService.class);
    playIntent.setAction(ACTION_PLAY);
    PendingIntent piPlay = PendingIntent.getService(mContext, 0, playIntent, 0);

    Intent nextIntet = new Intent(mContext, PlayAudioService.class);
    nextIntet.setAction(ACTION_NEXT);
    PendingIntent piNext = PendingIntent.getService(mContext, 0, nextIntet, 0);

    mBuilder.setSmallIcon(smallIcon)
                .setContentTitle("Title")
                .setContentText("Text")
                .setTicker("Ticker")
                .setWhen(0)
                //.setStyle(new NotificationCompat.BigTextStyle().bigText(title))
            .addAction (R.drawable.ic_previous, "Prev", piPrev)
                .addAction (R.drawable.ic_play,     "Play", piPlay)
                .addAction (R.drawable.ic_next,     "Next", piNext);

    Intent notifyIntent = new Intent(context, MainActivity.class);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    PendingIntent piNotify =
                PendingIntent.getActivity(
                mContext,
                0,
                notifyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
    mBuilder.setContentIntent(piNotify);
    mNotifyMgr.notify(mNotificationId, mBuilder.build());
}

In activity:

showNotification(this);

My Android target SDK version 15 and I am using latest version of support library v4. What am I missing and did not understand properly?

Your answer would be appreciated.

回答1:

Notification Actions were introduced in API 16.

This means that you should be setting your target SDK to 16 or above.

However, only Jelly Bean and above can take advantage of the Notification Actions - make sure to test this feature on those platforms.

NotificationCompat.Builder takes care of generating a Notification compatible with whatever API it is running on, so keep using it if you are going to be supporting Ice Cream Sandwich and older. If not, simply using Notification.Builder will suffice (after changing the target SDK of course).