1) В моем приложении пользователю может приходить множество нотификаций из FCM.
2) Если у пользователя открыто приложении, ему необходимо отобразить DialogFragment
3) Если DialogFragment уже отображен, то при следующем приходе нотификации, необходимо запретить повторное отображение этого DialogFragment.
4) Мой код диалога:
public final class NotificationEventDialog extends DialogFragment implements DialogInterface.OnKeyListener, View.OnClickListener {
private Activity mCurrentActivity;
private NotificationEventDialogListener mNotificationEventDialogListener;
public interface NotificationEventDialogListener {
void showEvent();
}
public NotificationEventDialog() {
}
public static NotificationEventDialog newInstance() {
NotificationEventDialog notificationEventDialog = new NotificationEventDialog();
notificationEventDialog.setCancelable(false);
return notificationEventDialog;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mCurrentActivity = (Activity)context;
try {
mNotificationEventDialogListener = (NotificationEventDialogListener) mCurrentActivity;
} catch (ClassCastException e) {
throw new ClassCastException(mCurrentActivity.toString() + " должен реализовывать NotificationEventDialogListener");
}
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(mCurrentActivity);
@SuppressLint("InflateParams") View view = inflater.inflate(R.layout.dialog_notification_event, null);
Button btnNotificationEventYes = view.findViewById(R.id.notification_event_dialog_yes);
btnNotificationEventYes.setOnClickListener(this);
Button btnNotificationEventNo = view.findViewById(R.id.notification_event_dialog_no);
btnNotificationEventNo.setOnClickListener(this);
AlertDialog.Builder builder = new AlertDialog.Builder(mCurrentActivity);
builder.setView(view);
return builder.create();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (getDialog() != null && getDialog().getWindow() != null) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().setOnKeyListener(this);
}
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onDetach() {
super.onDetach();
mCurrentActivity = null;
mNotificationEventDialogListener = null;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.notification_event_dialog_yes:
dismiss();
mNotificationEventDialogListener.showEvent();
break;
case R.id.notification_event_dialog_no:
dismiss();
break;
}
}
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
dismiss();
return true;
} else return false;
}
}
5) При каждой нотификации из FCM, создаю диалоговое окно:
DialogFragment notificationEventDialog = NotificationEventDialog.newInstance();
notificationEventDialog.show(getSupportFragmentManager(), "");
6) Как проверить, отображается ли в текущий момент уже DialogFragment? Просто получается, что каждый раз создается новый обьект этого окна, сделать его как Singleton не подходит, т.к. это ведет к утечке памяти.
Нашел ответ, в котором человек предлагает использовать Weak ссылки для решения этой проблемы:
Also you can store a weak link to the shown dialog in that singletone class. Using such method, you can detect is your dialog currently shown or not.
Также был такой ответ, созданием метода внутри диалога и проверять его отображение:
I suggest to save link to the dialog in single instance class. In that instance create method ensureShowDialog(Context context). That method would check is current shown dialog or not. If yes, you can show the dialog. In another casr you can pass new data you to the dialog.
Но, если честно, не совсем могу понять как использовать эти подсказки на практике. Пожалуйста, можете помочь с этим или подсказать другой путь? Зараннее спасибо.
!null
по тегу (который у вас сейчас "", но напишите что-нибудь осмысленное)notificationEventDialog.show(getSupportFragmentManager(), "df_notification_event");
а перед этим сделать типаFragment s = getSupportFragmentManager().findFragmentByTag("df_notification_event");
??if (getSupportFragmentManager().findFragmentByTag(YOUR_TAG) == null) {show}