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

如何在android中向通知添加按钮?,android,button,widget,notifications,Android,Button,Widget,Notifications,我的应用程序播放音乐,当用户通过从屏幕顶部(或平板电脑上通常从屏幕右下角)滑动来打开通知屏幕时,我想给他们一个按钮,让他们停止当前播放的音乐,并在需要时重新启动 我不打算把一个小部件放在用户的主屏幕上,而只是放在通知中。如何执行此操作?您可以创建操作意图(在本例中为停止播放),并将其作为操作按钮添加到通知中 Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class); snoozeIntent.setAction(ACTIO

我的应用程序播放音乐,当用户通过从屏幕顶部(或平板电脑上通常从屏幕右下角)滑动来打开通知屏幕时,我想给他们一个按钮,让他们停止当前播放的音乐,并在需要时重新启动


我不打算把一个小部件放在用户的主屏幕上,而只是放在通知中。如何执行此操作?

您可以创建操作意图(在本例中为停止播放),并将其作为操作按钮添加到通知中

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

请参阅。

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

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

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

        startService(i);
为了在服务类中接收意图并执行操作,我在服务的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);
} 希望这真的能帮助你。你将能够实现你想要的。祝您愉快:)


有关更多详细信息,请参阅此

将操作按钮添加到通知中

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);
欲了解更多详情,请访问

我认为除了
Ankit Gupta
答案之外,您还可以使用(API>21)添加本机视图:

资料来源:


您还可以创建自定义视图并将其显示在通知区域中,第一个答案非常好。

已测试,使用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>

您可以按如下方式添加按钮,并可以对该按钮执行操作,我也已按如下方式为我执行操作,请检查

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);
//更多支出(做你的事情)


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

  • 创建一个
    BroadCastReceiver
    类,以便在按下按钮时接收数据
  • 现在,在要创建通知的任何活动中-
  • 现在,在创建通知时使用此挂起意图,最后需要注册此广播以便在MyBroadCastReceiver类中接收它

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

    很抱歉,在这种情况下,我认为这是一个有效的问题,为什么这不是一个有效的问题?有些人只是否决了有意义的问题,但是为什么这是我在谷歌搜索中没有答案的最高结果…为了改进你的答案,你将添加没有图标的“文本”。p请提供创建意图的方法,在通知区域添加图标按钮,并将两者合并。“添加操作按钮”将在通知内容下方添加按钮,而不在通知内容下方。为什么您喜欢复制@rubenmiquelinoTo给出的上述答案?为了改进您的答案,您将添加不带图标的“文本”。请提供创建意图的方法,将图标按钮添加到通知区域并加入两者,然后如何接收意图。我没有尝试。但它似乎是唯一符合用户情况的
    完整的
    答案。
    
    <receiver android:name=".FloatingViewService$Receiver">
            <intent-filter>
                <action android:name="quit_action" />
            </intent-filter>
        </receiver>
    
    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);
    
      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
                    );
    
    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);
        }
    }
    
     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);
    
    BroadcastReceiver br = new MyBroadCastReceiver();
            IntentFilter filter = new IntentFilter("unique_id");
            registerReceiver(br, filter);