Внедрить расширение и свернуть уведомление android
Мне нужно реализовать расширение и свернуть уведомление в строке состояния для Android версии 4.0 и выше. У меня есть поиск в google для этого, но не получил никакого решения для реализации кода. У кого-нибудь есть идея, как реализовать это.
Спасибо заранее
Ответы
Ответ 1
Расширяемый Notification
является частным случаем Notification
Big View
. Если Big View
не находится в верхней части ящика уведомлений, он отображается как "закрыто" и может расширяться путем прокрутки. Цитата от разработчиков Android:
Большое вид уведомления появляется только при расширении уведомления, которое происходит, когда уведомление находится в верхней части окна уведомления, или когда пользователь расширяет уведомление с помощью жестов. Расширенные уведомления доступны начиная с Android 4.1.
Big View
Notification
можно создать следующим образом:
Notification notification = new Notification.BigTextStyle(builder)
.bigText(myText).build();
или
Notification notification = new Notification.BigPictureStyle(builder)
.bigPicture(
BitmapFactory.decodeResource(getResources(),
R.drawable.my_picture)).build();
Здесь - учебник.
Ответ 2
Notification noti = new Notification.Builder()
... // The same notification properties as the others
.setStyle(new Notification.BigPictureStyle().bigPicture(mBitmap))
.build();
Вы меняете
.setStyle(new NotificationCompat.BigTextStyle().bigText(th_alert))
вместе с объявлением ОК !!!
notification = new NotificationCompat.Builder(context)
Вот пример:
Вы можете установить код
Intent intent = new Intent(context, ReserveStatusActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
intent = new Intent(String.valueOf(PushActivity.class));
intent.putExtra("message", MESSAGE);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(PushActivity.class);
stackBuilder.addNextIntent(intent);
// PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// android.support.v4.app.NotificationCompat.BigTextStyle bigStyle = new NotificationCompat.BigTextStyle();
// bigStyle.bigText((CharSequence) context);
notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(th_title)
.setContentText(th_alert)
.setAutoCancel(true)
// .setStyle(new Notification.BigTextStyle().bigText(th_alert) ตัวเก่า
// .setStyle(new NotificationCompat.BigTextStyle().bigText(th_title))
.setStyle(new NotificationCompat.BigTextStyle().bigText(th_alert))
.setContentIntent(pendingIntent)
.setNumber(++numMessages)
.build();
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager.notify(1000, notification);
или же
private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
// .setContentTitle(notification.getTitle())
.setContentTitle(getResources().getText(R.string.app_name))
.setContentText(notification.getBody())
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(notification.getBody()))
.setContentInfo(notification.getTitle())
.setLargeIcon(icon)
.setColor(Color.RED)
.setSmallIcon(R.drawable.logo);
try {
String picture_url = data.get("picture_url");
if (picture_url != null && !"".equals(picture_url)) {
URL url = new URL(picture_url);
Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
notificationBuilder.setStyle(
new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
);
}
} catch (IOException e) {
e.printStackTrace();
}
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.YELLOW, 1000, 300);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
Ответ 3
Мы не можем создавать расширяемое уведомление в следующих версиях Android версии 4.1.
Но вместо этого мы можем сделать это, чтобы мы могли уложить уведомления, и тогда мы можем установить ожидающее намерения нашу довольно обычную деятельность, которая показывает все уведомления в списке.
Пользователь будет рад видеть это:)
Ответ 4
Есть метод для этой функции, вы можете показать маленький значок, когда уведомление свернуто, и показать большой, когда уведомление развернуто.
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.notification)
var notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.new_post)
.setContentTitle(imageTitle)
.setContentText(imageDescription)
.setLargeIcon(bitmap)
.setStyle(NotificationCompat.BigPictureStyle()
.bigPicture(bitmap)
.bigLargeIcon(null))
.build()
Ответ 5
Я не смог установить новый экземпляр нового NotificationCompat.BigTextStyle() в методе .setStyle() Notification. Поэтому я использовал приведенный ниже новый экземпляр нового Notification.BigTextStyle() в .setStyle().
Notification builder =new Notification.Builder(this)
.setSmallIcon(Notification_icons[icon])
.setContentTitle(title)
.setContentText(description)
.setChannelId(channelID_Default)
.setOngoing(true)
.setStyle(new Notification.BigTextStyle()
.bigText(description))
.build();