Как реализовать устаревшие методы уведомления
У меня небольшая проблема, но я не понимаю, как это сделать.
Я создал class для предоставления уведомлений, но эти строки отмечены как устаревшие:
... Notification notification = new Notification(icon, text, time); // deprecated in API level 11 ... notification.setLatestEventInfo(this, title, text, contentIntent); // deprecated in API level 11 ...
Альтернативные методы:
- Откройте приложение после нажатия кнопки «Уведомление»
- Отмена уведомления об удалении приложения из многозадачной панели
- Как выполнить метод, нажав на уведомление
- Определите addAction для уведомлений Android
- возобновление деятельности извещения
... Notification noti = new Notification.Builder(mContext) .setContentTitle("New mail from " + sender.toString()) .setContentText(subject) .setSmallIcon(R.drawable.new_mail) .setLargeIcon(aBitmap) .build(); // available from API level 11 and onwards ...
при... Notification noti = new Notification.Builder(mContext) .setContentTitle("New mail from " + sender.toString()) .setContentText(subject) .setSmallIcon(R.drawable.new_mail) .setLargeIcon(aBitmap) .build(); // available from API level 11 and onwards ...
Могу ли я написать код что-то вроде:
if(API_level < 11) { ... Notification notification = new Notification(icon, text, time); // deprecated in API level 11 ... notification.setLatestEventInfo(this, title, text, contentIntent); // deprecated in API level 11 ... } else { ... Notification noti = new Notification.Builder(mContext) .setContentTitle("New mail from " + sender.toString()) .setContentText(subject) .setSmallIcon(R.drawable.new_mail) .setLargeIcon(aBitmap) .build(); // available from API level 11 and onwards ... }
приif(API_level < 11) { ... Notification notification = new Notification(icon, text, time); // deprecated in API level 11 ... notification.setLatestEventInfo(this, title, text, contentIntent); // deprecated in API level 11 ... } else { ... Notification noti = new Notification.Builder(mContext) .setContentTitle("New mail from " + sender.toString()) .setContentText(subject) .setSmallIcon(R.drawable.new_mail) .setLargeIcon(aBitmap) .build(); // available from API level 11 and onwards ... }
Я предоставляю минимальную версию sdk как «8».
Редактировать:
Мне понравилось:
int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB){ Notification notification = new Notification(icon, text, time); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, TaskDetails.class), 0); notification.setLatestEventInfo(this, title, text, contentIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; mNM.notify(NOTIFICATION, notification); } else { // what to write here }
Что я могу написать для else
части?
- Уведомления с несколькими линиями в Интернете, такие как приложение Gmail
- Как воспроизвести звук уведомления об андроиде
- Обнаруживать новое уведомление для Android
- Истекает ли идентификатор регистрации GCM?
- Проверьте, включены ли локальные уведомления в IOS 8
- Проверить доступ к уведомлениям с помощью NotificationListenerService
- Android - создайте уведомление, TaskStackBuilder.addParentStack не работает
- Уведомления Android с кнопками на нем
Вот как я пришел к решению:
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) { notification = new Notification(icon, text, time); notification.setLatestEventInfo(this, title, text, contentIntent); // This method is removed from the Android 6.0 notification.flags |= Notification.FLAG_AUTO_CANCEL; mNM.notify(NOTIFICATION, notification); } else { NotificationCompat.Builder builder = new NotificationCompat.Builder( this); notification = builder.setContentIntent(contentIntent) .setSmallIcon(icon).setTicker(text).setWhen(time) .setAutoCancel(true).setContentTitle(title) .setContentText(text).build(); mNM.notify(NOTIFICATION, notification); }
Редактировать:
Вышеупомянутое решение работает. Тем не менее, поскольку был введен class NotificationCompat.Builder
, мы можем пропустить условие if для проверки, которое сравнивает текущую версию API. Итак, мы можем просто удалить условие if...else
и перейти к:
NotificationCompat.Builder builder = new NotificationCompat.Builder( this); notification = builder.setContentIntent(contentIntent) .setSmallIcon(icon).setTicker(text).setWhen(time) .setAutoCancel(true).setContentTitle(title) .setContentText(text).build(); mNM.notify(NOTIFICATION, notification);
Это правильный способ получить уровень.
final int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion < Build.VERSION_CODES.HONEYCOMB) { ... Notification notification = new Notification(icon, text, time); // deprecated in API level 11 ... notification.setLatestEventInfo(this, title, text, contentIntent); // deprecated in API level 11 ... } else { Notification noti = new Notification.Builder(mContext) .setContentTitle("New mail from " + sender.toString()) .setContentText(subject) .setSmallIcon(R.drawable.new_mail) .setLargeIcon(aBitmap) .build(); // available from API level 11 and onwards }
приfinal int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion < Build.VERSION_CODES.HONEYCOMB) { ... Notification notification = new Notification(icon, text, time); // deprecated in API level 11 ... notification.setLatestEventInfo(this, title, text, contentIntent); // deprecated in API level 11 ... } else { Notification noti = new Notification.Builder(mContext) .setContentTitle("New mail from " + sender.toString()) .setContentText(subject) .setSmallIcon(R.drawable.new_mail) .setLargeIcon(aBitmap) .build(); // available from API level 11 and onwards }
Все коды версий можно найти на этой ссылке разработчика .