-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathIterableInAppFragmentHTMLNotification.java
More file actions
775 lines (668 loc) · 31.3 KB
/
IterableInAppFragmentHTMLNotification.java
File metadata and controls
775 lines (668 loc) · 31.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
package com.iterable.iterableapi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.ColorUtils;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.DialogFragment;
public class IterableInAppFragmentHTMLNotification extends DialogFragment implements IterableWebView.HTMLNotificationCallbacks {
private static final String BACK_BUTTON = "itbl://backButton";
private static final String TAG = "IterableInAppFragmentHTMLNotification";
private static final String HTML_STRING = "HTML";
private static final String BACKGROUND_ALPHA = "BackgroundAlpha";
private static final String INSET_PADDING = "InsetPadding";
private static final String CALLBACK_ON_CANCEL = "CallbackOnCancel";
private static final String MESSAGE_ID = "MessageId";
private static final String IN_APP_OPEN_TRACKED = "InAppOpenTracked";
private static final String IN_APP_BG_ALPHA = "InAppBgAlpha";
private static final String IN_APP_BG_COLOR = "InAppBgColor";
private static final String IN_APP_SHOULD_ANIMATE = "ShouldAnimate";
private static final int DELAY_THRESHOLD_MS = 500;
@Nullable
static IterableInAppFragmentHTMLNotification notification;
@Nullable
static IterableHelper.IterableUrlCallback clickCallback;
@Nullable
static IterableInAppLocation location;
private IterableWebView webView;
private boolean loaded;
private OrientationEventListener orientationListener;
private boolean callbackOnCancel = false;
private String htmlString;
private String messageId;
// Resize debouncing fields
private Handler resizeHandler;
private Runnable pendingResizeRunnable;
private float lastContentHeight = -1;
private static final int RESIZE_DEBOUNCE_DELAY_MS = 200;
private double backgroundAlpha; //TODO: remove in a future version
private Rect insetPadding;
private boolean shouldAnimate;
private double inAppBackgroundAlpha;
private String inAppBackgroundColor;
public static IterableInAppFragmentHTMLNotification createInstance(@NonNull String htmlString, boolean callbackOnCancel, @NonNull IterableHelper.IterableUrlCallback clickCallback, @NonNull IterableInAppLocation location, @NonNull String messageId, @NonNull Double backgroundAlpha, @NonNull Rect padding) {
return IterableInAppFragmentHTMLNotification.createInstance(htmlString, callbackOnCancel, clickCallback, location, messageId, backgroundAlpha, padding, false, new IterableInAppMessage.InAppBgColor(null, 0.0f));
}
public static IterableInAppFragmentHTMLNotification createInstance(@NonNull String htmlString, boolean callbackOnCancel, @NonNull IterableHelper.IterableUrlCallback clickCallback, @NonNull IterableInAppLocation location, @NonNull String messageId, @NonNull Double backgroundAlpha, @NonNull Rect padding, @NonNull boolean shouldAnimate, IterableInAppMessage.InAppBgColor inAppBgColor) {
notification = new IterableInAppFragmentHTMLNotification();
Bundle args = new Bundle();
args.putString(HTML_STRING, htmlString);
args.putBoolean(CALLBACK_ON_CANCEL, callbackOnCancel);
args.putString(MESSAGE_ID, messageId);
args.putDouble(BACKGROUND_ALPHA, backgroundAlpha);
args.putParcelable(INSET_PADDING, padding);
args.putString(IN_APP_BG_COLOR, inAppBgColor.bgHexColor);
args.putDouble(IN_APP_BG_ALPHA, inAppBgColor.bgAlpha);
args.putBoolean(IN_APP_SHOULD_ANIMATE, shouldAnimate);
IterableInAppFragmentHTMLNotification.clickCallback = clickCallback;
IterableInAppFragmentHTMLNotification.location = location;
notification.setArguments(args);
return notification;
}
/**
* Returns the notification instance currently being shown
*
* @return notification instance
*/
public static IterableInAppFragmentHTMLNotification getInstance() {
return notification;
}
/**
* HTML In-App Notification
*/
public IterableInAppFragmentHTMLNotification() {
this.loaded = false;
this.backgroundAlpha = 0;
this.messageId = "";
insetPadding = new Rect();
this.setStyle(DialogFragment.STYLE_NO_FRAME, androidx.appcompat.R.style.Theme_AppCompat_NoActionBar);
}
@Override
public void onStart() {
super.onStart();
// Set dialog positioning after the dialog is created and shown (only for non-fullscreen)
Dialog dialog = getDialog();
if (dialog != null && getInAppLayout(insetPadding) != InAppLayout.FULLSCREEN) {
applyWindowGravity(dialog.getWindow(), "onStart");
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
htmlString = args.getString(HTML_STRING, null);
callbackOnCancel = args.getBoolean(CALLBACK_ON_CANCEL, false);
messageId = args.getString(MESSAGE_ID);
backgroundAlpha = args.getDouble(BACKGROUND_ALPHA);
insetPadding = args.getParcelable(INSET_PADDING);
inAppBackgroundAlpha = args.getDouble(IN_APP_BG_ALPHA);
inAppBackgroundColor = args.getString(IN_APP_BG_COLOR, null);
shouldAnimate = args.getBoolean(IN_APP_SHOULD_ANIMATE);
}
notification = this;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity(), getTheme()) {
@Override
public void onBackPressed() {
IterableInAppFragmentHTMLNotification.this.onBackPressed();
hideWebView();
}
};
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (callbackOnCancel && clickCallback != null) {
clickCallback.execute(null);
}
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set window gravity for the dialog (only for non-fullscreen)
if (getInAppLayout(insetPadding) != InAppLayout.FULLSCREEN) {
applyWindowGravity(dialog.getWindow(), "onCreateDialog");
}
if (getInAppLayout(insetPadding) == InAppLayout.FULLSCREEN) {
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else if (getInAppLayout(insetPadding) != InAppLayout.TOP) {
// For TOP layout in-app, status bar will be opaque so that the in-app content does not overlap with translucent status bar.
// For other non-fullscreen in-apps layouts (BOTTOM and CENTER), status bar will be translucent
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
return dialog;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
if (getInAppLayout(insetPadding) == InAppLayout.FULLSCREEN) {
getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
// Set initial window gravity based on inset padding (only for non-fullscreen)
if (getInAppLayout(insetPadding) != InAppLayout.FULLSCREEN) {
applyWindowGravity(getDialog().getWindow(), "onCreateView");
}
webView = createWebViewSafely(getContext());
if (webView == null) {
dismissAllowingStateLoss();
return null;
}
webView.setId(R.id.webView);
webView.createWithHtml(this, htmlString);
if (orientationListener == null) {
orientationListener = new OrientationEventListener(getContext(), SensorManager.SENSOR_DELAY_NORMAL) {
private int lastOrientation = -1;
// Resize the webView on device rotation
public void onOrientationChanged(int orientation) {
if (loaded && webView != null) {
// Only trigger on significant orientation changes (90 degree increments)
int currentOrientation = roundToNearest90Degrees(orientation);
if (currentOrientation != lastOrientation && lastOrientation != -1) {
lastOrientation = currentOrientation;
// Use longer delay for orientation changes to allow layout to stabilize
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
IterableLogger.d(TAG, "Orientation changed, triggering resize");
runResizeScript();
}
}, 1500); // Increased delay for better stability
} else if (lastOrientation == -1) {
lastOrientation = currentOrientation;
}
}
}
};
}
orientationListener.enable();
// Create a FrameLayout as the main container for better positioning control
FrameLayout frameLayout = new FrameLayout(this.getContext());
// Check if this is a full screen in-app
InAppLayout inAppLayout = getInAppLayout(insetPadding);
boolean isFullScreen = (inAppLayout == InAppLayout.FULLSCREEN);
if (isFullScreen) {
// For full screen in-apps, use MATCH_PARENT for both container and WebView
// Use FrameLayout.LayoutParams for direct child of FrameLayout
FrameLayout.LayoutParams webViewParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
);
frameLayout.addView(webView, webViewParams);
} else {
// For non-fullscreen in-apps, use the new layout structure with positioning
// Create a RelativeLayout as a wrapper for the WebView
RelativeLayout webViewContainer = new RelativeLayout(this.getContext());
int gravity = getVerticalLocation(insetPadding);
// Set FrameLayout gravity based on positioning
FrameLayout.LayoutParams containerParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT
);
if (gravity == Gravity.CENTER_VERTICAL) {
containerParams.gravity = Gravity.CENTER;
} else if (gravity == Gravity.TOP) {
containerParams.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
} else if (gravity == Gravity.BOTTOM) {
containerParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
}
// Add WebView to the RelativeLayout container with WRAP_CONTENT for proper sizing
RelativeLayout.LayoutParams webViewParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
webViewParams.addRule(RelativeLayout.CENTER_IN_PARENT);
webViewContainer.addView(webView, webViewParams);
// Add the container to the FrameLayout
frameLayout.addView(webViewContainer, containerParams);
}
if (savedInstanceState == null || !savedInstanceState.getBoolean(IN_APP_OPEN_TRACKED, false)) {
IterableApi.sharedInstance.trackInAppOpen(messageId, location);
}
prepareToShowWebView();
return frameLayout;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Handle edge-to-edge insets with modern approach (only for non-fullscreen)
// Full screen in-apps should not have padding from system bars
if (getInAppLayout(insetPadding) != InAppLayout.FULLSCREEN) {
ViewCompat.setOnApplyWindowInsetsListener(view, (v, insets) -> {
Insets sysBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(0, sysBars.top, 0, sysBars.bottom);
return insets;
});
}
}
public void setLoaded(boolean loaded) {
this.loaded = loaded;
}
/**
* Sets up the webView and the dialog layout
*/
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(IN_APP_OPEN_TRACKED, true);
}
/**
* On Stop of the dialog
*/
@Override
public void onStop() {
if (orientationListener != null) {
orientationListener.disable();
}
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
// Clean up pending resize operations
if (resizeHandler != null && pendingResizeRunnable != null) {
resizeHandler.removeCallbacks(pendingResizeRunnable);
}
pendingResizeRunnable = null;
resizeHandler = null;
if (this.getActivity() != null && this.getActivity().isChangingConfigurations()) {
return;
}
notification = null;
clickCallback = null;
location = null;
}
@Override
public void onUrlClicked(String url) {
IterableApi.sharedInstance.trackInAppClick(messageId, url, location);
IterableApi.sharedInstance.trackInAppClose(messageId, url, IterableInAppCloseAction.LINK, location);
if (clickCallback != null) {
clickCallback.execute(Uri.parse(url));
}
processMessageRemoval();
hideWebView();
}
/**
* Tracks a button click when the back button is pressed
*/
public void onBackPressed() {
IterableApi.sharedInstance.trackInAppClick(messageId, BACK_BUTTON);
IterableApi.sharedInstance.trackInAppClose(messageId, BACK_BUTTON, IterableInAppCloseAction.BACK, location);
processMessageRemoval();
}
private void prepareToShowWebView() {
try {
webView.setAlpha(0.0f);
webView.postDelayed(new Runnable() {
@Override
public void run() {
if (getContext() != null && getDialog() != null && getDialog().getWindow() != null) {
showInAppBackground();
showAndAnimateWebView();
}
}
}, DELAY_THRESHOLD_MS);
} catch (NullPointerException e) {
IterableLogger.e(TAG, "View not present. Failed to hide before resizing inapp");
}
}
private void showInAppBackground() {
animateBackground(new ColorDrawable(Color.TRANSPARENT), getInAppBackgroundDrawable());
}
private void hideInAppBackground() {
animateBackground(getInAppBackgroundDrawable(), new ColorDrawable(Color.TRANSPARENT));
}
private void animateBackground(Drawable from, Drawable to) {
if (from == null || to == null) {
return;
}
if (getDialog() == null || getDialog().getWindow() == null) {
IterableLogger.e(TAG, "Dialog or Window not present. Skipping background animation");
return;
}
Drawable[] layers = new Drawable[2];
layers[0] = from;
layers[1] = to;
TransitionDrawable transitionDrawable = new TransitionDrawable(layers);
transitionDrawable.setCrossFadeEnabled(true);
getDialog().getWindow().setBackgroundDrawable(transitionDrawable);
transitionDrawable.startTransition(IterableConstants.ITERABLE_IN_APP_BACKGROUND_ANIMATION_DURATION);
}
private ColorDrawable getInAppBackgroundDrawable() {
if (inAppBackgroundColor == null) {
IterableLogger.d(TAG, "Background Color does not exist. In App background animation will not be performed");
return null;
}
int backgroundColorWithAlpha;
try {
backgroundColorWithAlpha = ColorUtils.setAlphaComponent(Color.parseColor(inAppBackgroundColor), (int) (inAppBackgroundAlpha * 255));
} catch (IllegalArgumentException e) {
IterableLogger.e(TAG, "Background color could not be identified for input string \"" + inAppBackgroundColor + "\". Failed to load in-app background.");
return null;
}
ColorDrawable backgroundColorDrawable = new ColorDrawable(backgroundColorWithAlpha);
return backgroundColorDrawable;
}
private void showAndAnimateWebView() {
webView.setAlpha(1.0f);
webView.setVisibility(View.VISIBLE);
if (shouldAnimate) {
int animationResource;
InAppLayout inAppLayout = getInAppLayout(insetPadding);
switch (inAppLayout) {
case TOP:
animationResource = R.anim.slide_down_custom;
break;
case CENTER:
case FULLSCREEN:
animationResource = R.anim.fade_in_custom;
break;
case BOTTOM:
animationResource = R.anim.slide_up_custom;
break;
default:
animationResource = R.anim.fade_in_custom;
}
try {
Animation anim = AnimationUtils.loadAnimation(getContext(), animationResource);
anim.setDuration(IterableConstants.ITERABLE_IN_APP_ANIMATION_DURATION);
webView.startAnimation(anim);
} catch (Exception e) {
IterableLogger.e(TAG, "Failed to show inapp with animation");
}
}
}
private void hideWebView() {
if (shouldAnimate) {
int animationResource;
InAppLayout inAppLayout = getInAppLayout(insetPadding);
switch (inAppLayout) {
case TOP:
animationResource = R.anim.top_exit;
break;
case CENTER:
case FULLSCREEN:
animationResource = R.anim.fade_out_custom;
break;
case BOTTOM:
animationResource = R.anim.bottom_exit;
break;
default:
animationResource = R.anim.fade_out_custom;
}
try {
Animation anim = AnimationUtils.loadAnimation(getContext(),
animationResource);
anim.setDuration(IterableConstants.ITERABLE_IN_APP_ANIMATION_DURATION);
webView.startAnimation(anim);
} catch (Exception e) {
IterableLogger.e(TAG, "Failed to hide inapp with animation");
}
}
hideInAppBackground();
Runnable dismissWebViewRunnable = new Runnable() {
@Override
public void run() {
if (getContext() != null && getDialog() != null && getDialog().getWindow() != null) {
dismissAllowingStateLoss();
}
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
webView.postOnAnimationDelayed(dismissWebViewRunnable, 400);
} else {
webView.postDelayed(dismissWebViewRunnable, 400);
}
}
private void processMessageRemoval() {
IterableInAppMessage message = IterableApi.sharedInstance.getInAppManager().getMessageById(messageId);
if (message == null) {
IterableLogger.e(TAG, "Message with id " + messageId + " does not exist");
return;
}
if (message.isMarkedForDeletion() && !message.isConsumed()) {
IterableApi.sharedInstance.getInAppManager().removeMessage(message, null, null);
}
}
@Override
public void runResizeScript() {
// Initialize handler lazily with main looper to avoid Looper issues in tests
if (resizeHandler == null) {
resizeHandler = new Handler(Looper.getMainLooper());
}
// Cancel any pending resize operation
if (pendingResizeRunnable != null) {
resizeHandler.removeCallbacks(pendingResizeRunnable);
}
// Schedule a debounced resize operation
pendingResizeRunnable = new Runnable() {
@Override
public void run() {
performResizeWithValidation();
}
};
resizeHandler.postDelayed(pendingResizeRunnable, RESIZE_DEBOUNCE_DELAY_MS);
}
private void performResizeWithValidation() {
if (webView == null) {
IterableLogger.w(TAG, "WebView is null, skipping resize");
return;
}
float currentHeight = webView.getContentHeight();
// Validate content height
if (currentHeight <= 0) {
IterableLogger.w(TAG, "Invalid content height: " + currentHeight + "dp, skipping resize");
return;
}
// Check if height has stabilized (avoid unnecessary resizes for same height)
if (Math.abs(currentHeight - lastContentHeight) < 1.0f) {
IterableLogger.d(TAG, "Content height unchanged (" + currentHeight + "dp), skipping resize");
return;
}
lastContentHeight = currentHeight;
IterableLogger.d(
TAG,
"💚 Resizing in-app to height: " + currentHeight + "dp"
);
resize(currentHeight);
}
/**
* Resizes the dialog window based upon the size of its webView HTML content
*
* @param height
*/
public void resize(final float height) {
final Activity activity = getActivity();
if (activity == null) {
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
// Since this is run asynchronously, notification might've been dismissed already
if (getContext() == null || notification == null || notification.getDialog() == null ||
notification.getDialog().getWindow() == null || !notification.getDialog().isShowing()) {
return;
}
DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();
Window window = notification.getDialog().getWindow();
Rect insetPadding = notification.insetPadding;
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
// Get the correct screen size based on api level
// https://stackoverflow.com/questions/35780980/getting-the-actual-screen-height-android
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
display.getRealSize(size);
} else {
display.getSize(size);
}
int webViewWidth = size.x;
int webViewHeight = size.y;
//Check if the dialog is full screen
if (insetPadding.bottom == 0 && insetPadding.top == 0) {
//Handle full screen
window.setLayout(webViewWidth, webViewHeight);
getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
// Resize the WebView directly with explicit size
float relativeHeight = height * getResources().getDisplayMetrics().density;
int newWebViewWidth = getResources().getDisplayMetrics().widthPixels;
int newWebViewHeight = (int) relativeHeight;
// Set WebView to explicit size
RelativeLayout.LayoutParams webViewParams = new RelativeLayout.LayoutParams(newWebViewWidth, newWebViewHeight);
// Apply positioning based on gravity
int resizeGravity = getVerticalLocation(insetPadding);
IterableLogger.d(TAG, "Resizing WebView directly - gravity: " + resizeGravity + " size: " + newWebViewWidth + "x" + newWebViewHeight + "px for inset padding: " + insetPadding);
if (resizeGravity == Gravity.CENTER_VERTICAL) {
webViewParams.addRule(RelativeLayout.CENTER_IN_PARENT);
IterableLogger.d(TAG, "Applied CENTER_IN_PARENT to WebView");
} else if (resizeGravity == Gravity.TOP) {
webViewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
webViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
IterableLogger.d(TAG, "Applied TOP alignment to WebView");
} else if (resizeGravity == Gravity.BOTTOM) {
webViewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
webViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
IterableLogger.d(TAG, "Applied BOTTOM alignment to WebView");
}
// Make dialog full screen to allow proper positioning
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
// Apply the new layout params to WebView
webView.setLayoutParams(webViewParams);
// Force layout updates
webView.requestLayout();
if (webView.getParent() instanceof ViewGroup) {
((ViewGroup) webView.getParent()).requestLayout();
}
IterableLogger.d(TAG, "Applied explicit size and positioning to WebView: " + newWebViewWidth + "x" + newWebViewHeight);
}
} catch (IllegalArgumentException e) {
IterableLogger.e(TAG, "Exception while trying to resize an in-app message", e);
}
}
});
}
/**
* Returns the vertical position of the dialog for the given padding
*
* @param padding
* @return
*/
int getVerticalLocation(Rect padding) {
int gravity = Gravity.CENTER_VERTICAL;
if (padding.top == 0 && padding.bottom < 0) {
gravity = Gravity.TOP;
} else if (padding.top < 0 && padding.bottom == 0) {
gravity = Gravity.BOTTOM;
}
return gravity;
}
/**
* Rounds an orientation value to the nearest 90-degree increment.
* This is used to detect significant orientation changes (portrait/landscape).
*
* The calculation rounds to the nearest multiple of 90 by adding 45 before dividing.
* For positive numbers, uses integer division (which truncates toward zero).
* For negative numbers, uses floor division to correctly round toward negative infinity.
*
* @param orientation The orientation value in degrees (typically 0-359 from OrientationEventListener)
* @return The orientation rounded to the nearest 90-degree increment (0, 90, 180, 270, or 360)
*/
static int roundToNearest90Degrees(int orientation) {
if (orientation >= 0) {
// For positive numbers, integer division truncates toward zero
// (0 + 45) / 90 = 0, (44 + 45) / 90 = 0, (45 + 45) / 90 = 1
return ((orientation + 45) / 90) * 90;
} else {
// For negative numbers, use floor division to round toward negative infinity
// Math.floor((-46 + 45) / 90.0) = Math.floor(-1/90.0) = -1, so -1 * 90 = -90
return (int) (Math.floor((orientation + 45.0) / 90.0) * 90);
}
}
/**
* Sets the window gravity based on inset padding
*
* @param window The dialog window to configure
* @param context Debug context string for logging
*/
private void applyWindowGravity(Window window, String context) {
if (window == null) {
return;
}
WindowManager.LayoutParams windowParams = window.getAttributes();
int gravity = getVerticalLocation(insetPadding);
if (gravity == Gravity.CENTER_VERTICAL) {
windowParams.gravity = Gravity.CENTER;
} else if (gravity == Gravity.TOP) {
windowParams.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
} else if (gravity == Gravity.BOTTOM) {
windowParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
}
window.setAttributes(windowParams);
IterableLogger.d(TAG, "Set window gravity in " + context + ": " + windowParams.gravity);
}
InAppLayout getInAppLayout(Rect padding) {
if (padding.top == 0 && padding.bottom == 0) {
return InAppLayout.FULLSCREEN;
} else if (padding.top == 0 && padding.bottom < 0) {
return InAppLayout.TOP;
} else if (padding.top < 0 && padding.bottom == 0) {
return InAppLayout.BOTTOM;
} else {
return InAppLayout.CENTER;
}
}
private IterableWebView createWebViewSafely(Context context) {
try {
return new IterableWebView(context);
} catch (Resources.NotFoundException e) {
IterableLogger.e(TAG, "Failed to create WebView - system WebView resource issue", e);
return null;
} catch (RuntimeException e) {
IterableLogger.e(TAG, "Failed to create WebView - unexpected error", e);
return null;
}
}
}
enum InAppLayout {
TOP,
BOTTOM,
CENTER,
FULLSCREEN
}