如何在Android中向通知添加按钮?


84

我的应用播放音乐,并且当用户通过从屏幕顶部(或通常在平板电脑屏幕的右下角)滑动打开通知屏幕时,我想向他们显示一个按钮,以停止当前正在播放的音乐,并在出现以下情况时重新开始播放他们要。

我不打算将小部件放在用户的主屏幕上,而只是放在通知中。我怎样才能做到这一点?


在那种情况下,我很抱歉
坦率的说

62
我认为这是一个有效的问题
hunterp

7
这怎么不是一个有效的问题?
Radu

3
有些人只是拒绝有意义的问题,但是为什么

7
这是顶级的结果在我的谷歌搜索,并没有答案...

Answers:


11

您可以为该动作创建一个意图(在这种情况下,请停止播放)并将其作为动作按钮添加到通知中。

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

请参考Android文档


为了改善您的答案,您将添加不带图标的“文本”。请使用orovide方法创建意图,将图标按钮添加到通知区域并同时加入两者,然后如何接收意图。
tabebqena

8

向通知添加操作按钮

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

有关更多详细信息,请访问 https://developer.android.com/training/notify-user/build-notification.html


为了改善您的答案,您将添加不带图标的“文本”。请使用orovide创建意图的方法,在通知区域中添加图标按钮,然后将两者都加入。
tabebqena

“添加操作按钮”会将按钮添加到通知内容下方,而不是其中。
tabebqena

4

我将尝试提供一种我已经使用的解决方案,并且大多数音乐播放器也使用相同的技术在通知栏中显示播放器控件。

我正在运行一个用于管理Media Player及其所有控件的服务。活动用户控件通过向服务发送意图来与服务交互,例如

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

        startService(i);

在Service类中接收意图并执行操作我正在Service的onStartCommand方法中使用以下代码

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


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

现在要确切回答您的问题,以显示带有播放控件的通知。您可以调用以下方法来显示带有控件的通知。

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

}希望这对您有所帮助。您将能够实现自己想要的。祝您编码愉快:)


1
我没有尝试。但这似乎是针对用户案例的唯一complete答案fit
tabebqena

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

请参考此以获得更多详细信息,请点击这里


1

我认为,在Ankit Gupta答案旁边 ,您可以使用MediaSession (API> 21)添加本机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);

资料来源:教程

您还可以创建自定义视图并将其显示在通知区域中,这里的第一个答案很棒。


1

经过测试的android Pie工作代码。这些都在同一个服务类中。

显示通知:

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

辅助功能:

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

处理动作:

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;

        }

    }
}

您还需要更新清单:

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

1

您可以按如下所示添加按钮,也可以对该按钮执行操作,我也为我做了如下操作,请检查。

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(尽你所能)

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

0

我不知道这是否是正确的方法,但是它有效。

  1. 创建一个BroadCastReceiver类以在按下按钮时接收数据。
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. 现在,在您要创建通知的任何活动中-
 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. 现在,在创建通知时使用此挂起的意图,最后需要注册此广播才能在MyBroadCastReceiver类中接收它。
BroadcastReceiver br = new MyBroadCastReceiver();
        IntentFilter filter = new IntentFilter("unique_id");
        registerReceiver(br, filter);

现在,如果您想在按下按钮时执行某些操作,则可以onReceive()MyBroadCastReceiver类的方法中执行此操作。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.