У меня есть опция «Поделиться» в трее уведомлений. Итак, я использовал 2 пользовательских представления в своем коде.
1. Expandable Notification Layout
2. Normal Notification Layout
Пользовательский интерфейс работает нормально. Но уведомления работают некорректно. Если я нажимаю first notification or share first item
в уведомлении, все работает отлично. Но если я нажму last notification
, приложение откроется, но уведомление не будет удалено из панели уведомлений. Кроме того, странно то, что после нажатия на уведомление small icon
, которое появляется в строке состояния, исчезает, и теперь, если я нажимаю уведомление, оно не отвечает. Я отменяю уведомление. Вот почему второй раз, когда я нажимаю, он не работает. Этого не происходило, когда я использовал макет компоновщика по умолчанию для обычного просмотра. Вот мой код:
//настраиваем расширенный макет уведомлений
RemoteViews expandedView=new RemoteViews(context.getPackageName(), R.layout.custom_notification);
expandedView.setImageViewResource(R.id.image_logo, R.drawable.ic_launcher);
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa");
String time = dateFormat.format(new Date(when));
expandedView.setTextViewText(R.id.current_time, time);
expandedView.setTextViewText(R.id.title, context.getResources().getString(R.string.app_name));
expandedView.setTextViewText(R.id.text, message);
expandedView.setTextViewCompoundDrawables(R.id.share, R.drawable.gcm_share, 0, 0, 0);
// устанавливаем обычный макет уведомлений
RemoteViews collapsedView=new RemoteViews(context.getPackageName(), R.layout.custom_notification_normal_layout);
collapsedView.setTextViewText(R.id.text, message);
notificationId = ((int) System.currentTimeMillis() % 1000000);
//зарегистрируйте listenr для значка «Поделиться»
setBtnListeners(expandedView, requestID, message, context, notificationId);
`Bitmap largeIcon = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap()`;
//Создаем построитель уведомлений
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(context);
mNotifyBuilder
.setWhen(when)
.setSmallIcon(icon)
.setLargeIcon(largeIcon)
.setContentTitle(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
notification = mNotifyBuilder.build();
//назначаем соперников построителю уведомлений
notification.bigContentView = expandedView;
notification.contentView = collapsedView;
//создать ожидаемое намерение
Intent notificationIntent;
//notificationIntent = new Intent(context, Launcher.class);
notificationIntent = new Intent(context, SplashActivity.class);//Sritapana189
notificationIntent.putExtra(BundleKeys.NORMAL_PUSH, 1);
notificationIntent.putExtra(BundleKeys.DEFAULT_NOTI_NAV, nav);
notificationIntent.putExtra(BundleKeys.FROM_GCM, true);
notificationIntent.putExtra(ApplicationConstants.GCMKeys.GCM_NOTIFICATION_ID, notificationId);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, requestID, notificationIntent, 0); //Modified
notification.contentIntent = contentIntent;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notificationId, notification);
//Регистрация значка общего доступа в трее уведомлений
private static void setBtnListeners(RemoteViews notificationView, int requestId, String message, Context context, int notificationId) {
Intent shareBtnIntent = new Intent(context, GcmTransparentActivity.class);
shareBtnIntent.putExtra(ApplicationConstants.GCMKeys.BREAKING_NEWS, message);
shareBtnIntent.putExtra(ApplicationConstants.GCMKeys.GCM_NOTIFICATION_ID, notificationId);
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestId, shareBtnIntent, 0);
notificationView.setOnClickPendingIntent(R.id.share, pendingIntent);
}
//SplashActivity получает ожидающий Inent
// здесь я извлекаю данные полезной нагрузки и сохраняю их, а затем отменяю уведомление
Utility.cancelNotification(gcmNotificationId, getApplicationContext());
public static void cancelNotification(int id, Context ctx) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
nMgr.cancel(id);
}
Единственное изменение, которое я сделал в своем коде, — это добавление пользовательского макета для обычного вида. После этого изменения он ведет себя неправильно, когда щелкается последний элемент уведомления. Есть ли что-то, что мне не хватает. пожалуйста, помогите мне разобраться в этом странном вопросе.