Полный список
В Android 4.1 появилась возможность добавлять кнопки в уведомление.
Для этого используется метод addAction.
Сначала создаем PendingIntent, который будет вызван по нажатию на кнопку. Затем передаем его в метод addAction, а вместе с ним иконку и текст для кнопки.
При раскрытии уведомления будет отображена кнопка.
По нажатию на кнопку уведомление само не закроется. Если вам необходимо его закрыть, используйте cancel в обработчике нажатия.
Вы можете добавить до трех Action кнопок. Кнопки не должны дублировать действие, которое происходит по нажатию на уведомление.
На последних версиях Android почему-то не отображается иконка кнопки, только текст.
Reply
Начиная с API 24 появилась возможность добавить в уведомление строку ввода. Это может быть удобно, например, в чат-приложениях. Пользователь сможет ответить на сообщение прямо из уведомления.
Рассмотрим пример реализации:
Разбираем код по порядку.
У нас есть некий itemId. Это может быть, например, id чата, в который пришло новое сообщение.
Создаем Intent и PendingIntent. Тут ничего нового. Мы будем вызывать сервис MyService и передавать ему itemId. В PendingIntent используем itemId в качестве requestCode.
Далее создаем RemoteInput. Здесь настраиваем все, что касается поля ввода, которое будет отображено в уведомлении. В конструкторе билдера необходимо указать ключ, который мы в дальнейшем будем использовать, чтобы из Bundle достать текст, который введет пользователь. В метод setLabel можно передать текст, который будет использован как hint (подсказка) в поле ввода.
Создаем Action кнопку с помощью билдера. Передаем туда стандартный набор: иконку, текст и PendingIntent. А в метод addRemoteInput передаем ранее созданный RemoteInput. Это будет Action кнопка Reply, по нажатию на которую будет появляться строка ввода.
Далее используем созданный Action в билдере уведомления, создаем уведомление и отображаем его.
В методе notify используем itemId. Соответственно, зная id чата, мы всегда сможем обновить или удалить уведомление.
Обратите внимание, что PendingIntent, который мы создаем и используем в Action кнопке Reply, будет использован не по нажатию на уведомление, и даже не по нажатию на Reply. Он будет использован, когда пользователь нажмет на кнопку отправки текста.
В этом примере, кстати, по нажатию на уведомление, ничего не произодет, т.к. в билдере уведомления я не использовал метод setContentIntent, чтобы не усложнять пример.
В уведомлении создается Action кнопка Reply. Она открывает строку ввода.
По нажатию на кнопку отправки текста система запускает MyService, который мы указывали в PedningIntent, и отображает прогрессбар. Но он будет крутиться бесконечно, пока мы программно не обновим или не удалим уведомление.
Давайте посмотрим, как в MyService мы можем получить введенный пользователем текст и убрать прогрессбар из уведомления:
Методом RemoteInput.getResultsFromIntent достаем Bundle из Intent. Из этого Bundle можем достать текст, который вводил пользователь в уведомлении. Для этого используем ключ EXTRA_TEXT_REPLY (который ранее использовали в билдере RemoteInput).
Далее из Intent достаем itemId.
Теперь у нас есть id чата и текст, который ввел пользователь. Можем сохранить его в БД, отправить на сервер или сделать еще что-то. Это зависит от логики приложения.
Далее нам необходимо разобраться с уведомлением. Напомню, что после отправки текста оно отображает прогрессбар. В этом примере мы создаем простое уведомление с текстом Replied и заменяем им (используя тот же itemId в методе notify) то уведомление, из которого был отправлен текст.
Пробуем еще раз отправить текст из уведомления
На этот раз мы в обработчике обновили уведомление и прогрессбар пропал.
Что вы будете делать с уведомлением после отправки текста — это ваше решение. Например, вы можете просто удалить его. Либо, если вы в уведомлении отображаете последние сообщения чата, вы можете обновить это уведомление с учетом нового сообщения и снова сделать там кнопку Reply.
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Как назначить собственный метод для кнопки в уведомлении
Создавая кнопки в уведомлении нельзя просто назначить им слушатели, как мы привыкли делать редактируя интерфейс пользователя. Основным способом назначения действий в уведомлении являются интенты (Intent) — намерения.
И если для того, чтобы назначить кнопке действия перехода в какую-либо Activity достаточно просто создать соответствующий интент, внутри которого и будет описано необходимое действие, а именно — откуда и куда переходим, то в нашем случае необходимо будет сделать следующее: назначить кнопке намерение, передать ему Action для работы с интент фильтром, создать BroadcastReciver, который будет вылавливать наш Intent и уже тогда выполнять необходимый нам метод.
Итак, для начала создадим наше уведомление. В своем примере я вынес все следующие действия в отдельный метод sendNotification. Но прежде нам необходимо создать строку, в которую мы запишем ключ для того, чтобы наш приемник мог отловить именно наш Intent. Так как множество приложений постоянно вбрасывают интенты в систему, этот ключ должен быть уникальным
Теперь необходимо создать приемник BroadCastReciver. Для этого необходимо щелкнуть ПКМ по вашей папке app->New->Other->BroadcastReciver. Далее дайте ему имя, и в открывшемся файле нам необходимо убрать заглушку в виде вброса исключения, написав на ее месте наш метод
Но помимо этого нам необходимо настроить Intent Filter для нашего приемника, чтобы дать ему понять, какие именно Inetnt ему надо принимать. Для этого заходим в манифест и блоке кода нашего приемника прописываем Intent Filter, куда записываем содержимое строковой переменной BROADCAST_ACTION созданной в самом начале
Вот и все, теперь в случае нажатия на созданную нами кнопку в уведомлении будет запускаться метод, определенный в теле BroadcastReciver
Источник
Notification with button android
Пришло время научиться использовать такую вещь, как уведомления в Android ОС. Мы видим их регулярно в своих смартфонах и планшетах — различные приложения сообщают нам о разных событиях именно с помощью отображения Notification уведомлений в статус баре устройства. Пользователю остается только выдвинуть шторку вниз и увидеть, что же там ему пишет какая то программа.
Для создания собственных уведомлений нужно выполнить такие основные шаги:
— объявить уведомление и определить особенности его отображения в Status Bar ;
— определить внешний вид уведомления при раскрытии шторки устройства, а также действие по нажатию на тело уведомления;
— настроить желаемые особенности уведомления, типа звуковой сигнал при его появлении, мерцание экрана или закрытие уведомления после нажатия пользователя по нему;
— сообщить о своем уведомлении системе;
— наконец то запустить отображение Notification уведомления, используя его уникальный ID, который вы сами и задаете, а после выполнения задачи, стоящей перед сообщением, закрыть его, используя тот же уникальный ID.
Теперь перейдем от теории к практике и создадим приложение, которое будет провоцировать появление в системе уведомления о том, что нам нужно лучше усердствовать в учебе и при нажатии по нему будет выполняться переход на сайт. Появление уведомления будет сопровождаться феерверками звуковым сигналом, а при нажатии по нему пользователем, оно будет исчезать.
Создадим новый проект, выбираем Blank Activity, Android 2.2+. Пользовательский интерфейс приложения будет состоять из двух кнопок, при нажатии на одну будет появляться уведомление, при нажатии на другую оно будет исчезать. Открываем файл activity_main.xml и добавляем туда пару кнопок:
Теперь переходим в файл MainActivity.java и добавляем следующий код:
Запускаем и смотрим, что получилось:
Вот так, при нажатии на уведомление произойдет его закрытие и переход на сайт.
Источник
Custom Notifications for Android
Why custom notifications?
Arriving at Hootsuite, my first project was to revamp our Android push notifications — from single lines of text to ones that contained the same information as our in-app notifications. This would allow customers to reply to mentions, check out new followers, publish Instagram posts and much more right from their home screen, reducing the friction of their workflow. The original plan was to switch from InboxStyle to BigPictureStyle or BigTextStyle, but it soon became clear that default styles were not enough. They forced us to choose between showing media or text when we wanted to display images with multiline text, formatted to be consistent with our in-app user interface. This article will cover creating completely custom rich notifications with actions using the DecoratedCustomViewStyle introduced in API level 24.
The original notifications, using InboxStyle. Each one was a line of text in a single Android notification, and users had to enter the app to get more value out of them:
The first iteration using BigTextStyle and BigPictureStyle. We have a lot more information and actions, but it’s a tradeoff between text and media, and we can’t format or style the Views:
The final iteration using DecoratedCustomViewStyle. The Views are completely custom and support rich media, including images, videos and GIFs:
So let’s dive into the world of rich notifications! We’ll be making a sample app that can send this notification:
You can find the complete code for it here.
Starting with the basics
We’ll use NotificationCompat.Builder, the builder class that makes it easy to specify the appearance and behavior of our NotificationCompat object. (NotificationCompat includes the features introduced to the Notification class after API level 4 while remaining backwards compatible with devices that are at a lower API level.) Custom notifications start out like any other notification:
All notifications require these three fields to be set, although you won’t actually see them once you add your custom views. We’ll add two more lines:
This ensures that the notification is automatically cancelled and MainActivity launches when the user taps it.
XML files
Now let’s make the layout files for our custom views, which we’ll eventually inflate into RemoteViews objects. (RemoteViews is a view hierarchy that can be displayed outside of your app’s process, and the only View subclass that NotificationCompat.Builder will accept as an argument for CustomContentView or CustomContentBigView.) You can style your XML layout files however you want, but keep in mind that RemoteViews only support FrameLayout, LinearLayout, RelativeLayout, and GridLayout, and a limited set of View subclasses. If you want to customize both the collapsed and the expanded view, you’ll need to create a layout file for each of them.
Here’s the layout for our collapsed notification…
and our expanded one.
Side note on styles
My sample app’s layouts look similar to the default Android notifications. If you want your UI to be consistent with the Android design as well, notifications, like any other widget, have built-in default styles that you can apply. For example, I used
to style the timestamp.
Adding the information
Notifications are most interesting when they contain relevant, dynamic information. In the sample app, we’ll make the notification display whatever the user types and also set the time stamp to be the current time. We’ll create new RemoteViews objects using our XML files.
There are numerous setter methods that you can call to programmatically populate the view — just pass in the viewId and whatever you want to put there. The ones I ended up using were setTextViewText(), setImageViewResource() and setOnClickPendingIntent(), since together they provide the features of a standard Android notification.
Adding the actions
For the demo app, we’ll just make the button trigger a Toast message helpfully telling you which button you clicked. We’ll set a PendingIntent for the button using setOnClickPendingIntent(), which allows a foreign application, such as the home screen, to execute code with your application’s permissions. We’ll make an IntentService and call PendingIntent.getService() to retrieve a PendingIntent that starts the service, since all we want to do is display a Toast.
You’ll have to set the action string whenever you have multiple actions, so that you can do a switch statement in onHandleIntent. Since the IntentService runs on a background thread that doesn’t display UI, we’ll have to make a Handler object on the main thread to make the Toast show up.
In the actual Hootsuite app, we made the Toast on the main thread using RxJava:
Don’t forget to register your IntentService in AndroidManifest.xml!
By the way, the other options for creating a PendingIntent are getActivity() (the PendingIntent begins an Activity), getActivities() and getBroadcast() (the PendingIntent performs a broadcast, and could be better choices depending on what your intended actions are.
Almost done!
We’re ready to turn the NotificationCompat.Builder into a *real* NotificationCompat — just call builder.build().
You’ll have to get the system level NotificationManager from the system service.
Finally, we’ll call notificationManager.notify() to send the notification to the system. We’re passing in 0 as the id parameter but if you want your app to display multiple notifications, you’ll need to pass in a unique int each time.
Here’s our complete MainActivity.java:
Final note on sizing
Sizing will vary from device to device, so it’s important to make sure our layouts will fit on every screen. The height measurements are 64 dp for a collapsed notification and 256dp for an expanded. I ended up adding maxLine attributes to TextViews and maxHeight attributes to ImageViews to prevent elements from getting pushed off the screen.
Results
There were two main problems that rich notifications were meant to address: our old notifications didn’t contain enough information to be very useful to users, and Instagram publishing had a complicated workflow. We were happy to see that Instagram publishing notifications were the most used, with the “publish” action making up 85% of all user notification actions.
However, one customer sent feedback that he didn’t like the update because he received hundreds of notifications every day. This was fine when he’d have a single InboxStyle notification informing him that he had a few hundred unviewed messages, but when they arrived individually, they became distracting. We realized that actions are ideal for users who have enabled the few notifications that they find really important. For those with many notifications enabled, grouping their summaries into a single notification would be more useful. So now, with a simple check of the notification count, we’re sending the first four notifications as rich ones for users to action on and combining them once again into an InboxStyle notification when the count reaches five. After users clear it, the count resets and they’ll receive rich notifications again. After this change, the number of notifications cleared dropped significantly, to a tenth of what it was before. We’ll continue to listen to customer feedback and tweak notifications to improve the experience as much as possible.
Источник