Как добавить кнопку для уведомлений в Android? - программирование
Подтвердить что ты не робот

Как добавить кнопку для уведомлений в Android?

Мое приложение воспроизводит музыку, и когда пользователи открывают экран уведомлений, проведя пальцем по верхней части экрана (или, как правило, по правому нижнему углу экрана на планшетах), я хочу предоставить им кнопку, чтобы остановить воспроизводимую в настоящее время музыку и запустить ее снова, если они хотят.

Я не планирую помещать виджет на домашний экран пользователя, а просто в уведомления. Как я могу это сделать?

4b9b3361

Ответ 1

Вы можете создать намерение для действия (в этом случае прекратить играть) и добавить его в качестве кнопки действия в свое уведомление.

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.

Ответ 2

Добавить кнопку действия в уведомление

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

Ответ 3

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

Подробнее см. Нажмите здесь

Ответ 4

Я попытаюсь предоставить решение, которое я использовал, и большинство музыкальных проигрывателей также используют тот же метод, чтобы отображать элементы управления плеером в панели уведомлений.

Я запускаю службу, которая используется для управления Media Player и всеми его элементами управления. Активность Пользовательский элемент управления взаимодействует с Сервисом, отправив Intents в службу, например

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

        startService(i);

Чтобы получить намерения и выполнить действие в классе 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);

} Надеюсь, это действительно поможет вам. И вы сможете достичь того, чего хотите. Счастливого кодирования:)

Ответ 5

Я думаю, что помимо ответа 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);

Источник: учебник

Вы также можете создать собственное представление и отобразить его в области уведомлений, первый ответ здесь великолепен.

Ответ 6

проверено, рабочий код с 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>

Ответ 7

Вы можете добавить кнопку, как показано ниже, и можете выполнить действие с этой кнопкой, также я сделал для меня, как показано ниже,.

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