Всплывающее уведомление Android
Может вопрос банален и где-то его решение есть, но удовлетворяющего ответа я, к сожалению, найти не смог.
Как сделать всплывающее уведомление? У меня получилось только сделать так, чтобы оно просто приходило и было в самом низу списка уведомлений. Что нужно добавить в код?
Notification.Builder builder =
new Notification.Builder(this)
.setSmallIcon(R.drawable.icon_help)
.setContentTitle("Напоминание")
.setSubText("База вопросов").setStyle(new Notification.BigTextStyle().bigText("Новый вопрос!"));
Notification notification = builder.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
Ответы (1 шт):
Автор решения: Alex_Skvortsov
→ Ссылка
У меня некий конечный рабочий вариант получился таким:
class MainActivity : AppCompatActivity() {
companion object {
const val channelId = "just_random_string_395"
const val notifyId = 395
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onResume() {
super.onResume()
sendNotification()
}
private fun sendNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createChannel()
val notification = buildNotification()
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.cancel(notifyId)
manager.notify(notifyId, notification)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createChannel() {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val name = "Notification channel name"
val channel = NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH)
channel.description = "Notification channel description"
manager.createNotificationChannel(channel)
}
private fun buildNotification(): Notification {
val builder = notificationBuilder
builder.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Заголовок")
.setSubText("Описание сути уведомления")
.setStyle(NotificationCompat.BigTextStyle().bigText("Очень длинный текст...\nРеально очень длинный. \n Целых три строчки!"))
.priority = NotificationCompat.PRIORITY_MAX
return builder.build()
}
private val notificationBuilder
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) NotificationCompat.Builder(this, channelId)
else NotificationCompat.Builder(this, channelId)
}
Это стандартная активность в пустом приложении. Лишнего кода тут, вроде бы, нет.
Ваша ошибка, как я могу предположить, в том, что Вы не используете каналы уведомлений.
Надеюсь, это поможет.
Update Версия кода для тех, кто использует Java:
public class MainActivityJava extends AppCompatActivity {
private static final String channelId = "just_random_string_395";
private static final int notifyId = 395;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
sendNotification();
}
private void sendNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createChannel();
Notification notification = buildNotification();
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.cancel(notifyId);
manager.notify(notifyId, notification);
}
}
@RequiresApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String name = "Notification channel name";
NotificationChannel channel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Notification channel description");
if (manager != null)
manager.createNotificationChannel(channel);
}
private Notification buildNotification() {
NotificationCompat.Builder builder = notificationBuilder();
builder.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Заголовок")
.setSubText("Описание сути уведомления")
.setStyle(new NotificationCompat.BigTextStyle().bigText("Очень длинный текст...\nРеально очень длинный. \n Целых три строчки!"))
.setPriority(NotificationCompat.PRIORITY_MAX);
return builder.build();
}
private NotificationCompat.Builder notificationBuilder() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
return new NotificationCompat.Builder(this, channelId);
else return new NotificationCompat.Builder(this, channelId);
}
}