-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
TiBaseActivity.java
1778 lines (1545 loc) Β· 55.5 KB
/
TiBaseActivity.java
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2018 by Axway, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.titanium;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.KrollObject;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.KrollRuntime;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiMessenger;
import org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent;
import org.appcelerator.titanium.TiLifecycle.OnWindowFocusChangedEvent;
import org.appcelerator.titanium.TiLifecycle.interceptOnBackPressedEvent;
import org.appcelerator.titanium.TiLifecycle.OnActivityResultEvent;
import org.appcelerator.titanium.TiLifecycle.OnInstanceStateEvent;
import org.appcelerator.titanium.TiLifecycle.OnCreateOptionsMenuEvent;
import org.appcelerator.titanium.TiLifecycle.OnPrepareOptionsMenuEvent;
import org.appcelerator.titanium.proxy.ActionBarProxy;
import org.appcelerator.titanium.proxy.ActivityProxy;
import org.appcelerator.titanium.proxy.IntentProxy;
import org.appcelerator.titanium.proxy.TiToolbarProxy;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.proxy.TiWindowProxy;
import org.appcelerator.titanium.util.TiActivityResultHandler;
import org.appcelerator.titanium.util.TiActivitySupport;
import org.appcelerator.titanium.util.TiActivitySupportHelper;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiLocaleManager;
import org.appcelerator.titanium.util.TiMenuSupport;
import org.appcelerator.titanium.util.TiPlatformHelper;
import org.appcelerator.titanium.util.TiUIHelper;
import org.appcelerator.titanium.util.TiWeakList;
import org.appcelerator.titanium.view.TiActionBarStyleHandler;
import org.appcelerator.titanium.view.TiActivitySafeAreaMonitor;
import org.appcelerator.titanium.view.TiCompositeLayout;
import org.appcelerator.titanium.view.TiCompositeLayout.LayoutArrangement;
import org.appcelerator.titanium.view.TiInsetsProvider;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.PowerManager;
import android.os.RemoteException;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
/**
* The base class for all non tab Titanium activities. To learn more about Activities, see the
* <a href="http://developer.android.com/reference/android/app/Activity.html">Android Activity documentation</a>.
*/
public abstract class TiBaseActivity extends AppCompatActivity implements TiActivitySupport /*, ITiWindowHandler*/
{
private static final String TAG = "TiBaseActivity";
private boolean onDestroyFired = false;
private int originalOrientationMode = -1;
private boolean inForeground = false; // Indicates whether this activity is in foreground or not.
private TiWeakList<OnLifecycleEvent> lifecycleListeners = new TiWeakList<OnLifecycleEvent>();
private TiWeakList<OnWindowFocusChangedEvent> windowFocusChangedListeners =
new TiWeakList<OnWindowFocusChangedEvent>();
private TiWeakList<interceptOnBackPressedEvent> interceptOnBackPressedListeners =
new TiWeakList<interceptOnBackPressedEvent>();
private TiWeakList<OnInstanceStateEvent> instanceStateListeners = new TiWeakList<OnInstanceStateEvent>();
private TiWeakList<OnActivityResultEvent> onActivityResultListeners = new TiWeakList<OnActivityResultEvent>();
private TiWeakList<OnCreateOptionsMenuEvent> onCreateOptionsMenuListeners =
new TiWeakList<OnCreateOptionsMenuEvent>();
private TiWeakList<OnPrepareOptionsMenuEvent> onPrepareOptionsMenuListeners =
new TiWeakList<OnPrepareOptionsMenuEvent>();
private boolean sustainMode = false;
private Intent launchIntent = null;
private TiActionBarStyleHandler actionBarStyleHandler;
private TiActivitySafeAreaMonitor safeAreaMonitor;
public static class PermissionContextData
{
private final Integer requestCode;
private final KrollObject context;
private final KrollFunction callback;
public PermissionContextData(Integer requestCode, KrollFunction callback, KrollObject context)
{
this.requestCode = requestCode;
this.callback = callback;
this.context = context;
}
public Integer getRequestCode()
{
return requestCode;
}
public KrollFunction getCallback()
{
return callback;
}
public KrollObject getContext()
{
return context;
}
}
private static ConcurrentHashMap<Integer, PermissionContextData> callbackDataByPermission =
new ConcurrentHashMap<Integer, PermissionContextData>();
protected View layout;
protected TiActivitySupportHelper supportHelper;
protected int supportHelperId = -1;
protected TiWindowProxy window;
protected TiViewProxy view;
protected ActivityProxy activityProxy;
protected TiWeakList<ConfigurationChangedListener> configChangedListeners =
new TiWeakList<ConfigurationChangedListener>();
protected TiMenuSupport menuHelper;
protected Messenger messenger;
protected int msgActivityCreatedId = -1;
protected int msgId = -1;
//Storing the activity's dialogs and their persistence
private CopyOnWriteArrayList<DialogWrapper> dialogs = new CopyOnWriteArrayList<DialogWrapper>();
public TiWindowProxy lwWindow;
public boolean isResumed = false;
public static boolean canFinishRoot = true;
private boolean overridenLayout;
public static class DialogWrapper
{
boolean isPersistent;
Dialog dialog;
WeakReference<TiBaseActivity> dialogActivity;
public DialogWrapper(Dialog d, boolean persistent, WeakReference<TiBaseActivity> activity)
{
isPersistent = persistent;
dialog = d;
dialogActivity = activity;
}
public TiBaseActivity getActivity()
{
if (dialogActivity == null) {
return null;
} else {
return dialogActivity.get();
}
}
public void setActivity(WeakReference<TiBaseActivity> da)
{
dialogActivity = da;
}
public Dialog getDialog()
{
return dialog;
}
public void setDialog(Dialog d)
{
dialog = d;
}
public void release()
{
dialog = null;
dialogActivity = null;
}
public boolean getPersistent()
{
return isPersistent;
}
public void setPersistent(boolean p)
{
isPersistent = p;
}
}
public static interface ConfigurationChangedListener {
public void onConfigurationChanged(TiBaseActivity activity, Configuration newConfig);
}
/**
* @return the instance of TiApplication.
*/
public TiApplication getTiApp()
{
return (TiApplication) getApplication();
}
/**
* @return the window proxy associated with this activity.
*/
public TiWindowProxy getWindowProxy()
{
return this.window;
}
/**
* Sets the window proxy.
* @param proxy
*/
public void setWindowProxy(TiWindowProxy proxy)
{
this.window = proxy;
}
/**
* Sets the proxy for our layout (used for post layout event)
*
* @param proxy
*/
public void setLayoutProxy(TiViewProxy proxy)
{
if (layout instanceof TiCompositeLayout) {
((TiCompositeLayout) layout).setProxy(proxy);
}
}
/**
* Sets the view proxy.
* @param proxy
*/
public void setViewProxy(TiViewProxy proxy)
{
this.view = proxy;
}
/**
* @return activity proxy associated with this activity.
*/
public ActivityProxy getActivityProxy()
{
return activityProxy;
}
public void addDialog(DialogWrapper d)
{
if ((d != null) && !dialogs.contains(d)) {
dialogs.add(d);
}
}
public void removeDialog(Dialog d)
{
for (int i = 0; i < dialogs.size(); i++) {
DialogWrapper p = dialogs.get(i);
if (p.getDialog().equals(d)) {
p.release();
dialogs.remove(i);
return;
}
}
}
public void setActivityProxy(ActivityProxy proxy)
{
this.activityProxy = proxy;
}
/**
* @return the activity's current layout.
*/
public View getLayout()
{
return layout;
}
public void setLayout(View layout)
{
this.layout = layout;
}
public void addConfigurationChangedListener(ConfigurationChangedListener listener)
{
configChangedListeners.add(new WeakReference<ConfigurationChangedListener>(listener));
}
public void removeConfigurationChangedListener(ConfigurationChangedListener listener)
{
configChangedListeners.remove(listener);
}
protected boolean getIntentBoolean(String property, boolean defaultValue)
{
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(property)) {
return intent.getBooleanExtra(property, defaultValue);
}
}
return defaultValue;
}
protected int getIntentInt(String property, int defaultValue)
{
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(property)) {
return intent.getIntExtra(property, defaultValue);
}
}
return defaultValue;
}
protected String getIntentString(String property, String defaultValue)
{
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(property)) {
return intent.getStringExtra(property);
}
}
return defaultValue;
}
protected void updateTitle()
{
if (window == null)
return;
if (window.hasProperty(TiC.PROPERTY_TITLE)) {
String oldTitle = (String) getTitle();
String newTitle = TiConvert.toString(window.getProperty(TiC.PROPERTY_TITLE));
if (oldTitle == null) {
oldTitle = "";
}
if (newTitle == null) {
newTitle = "";
}
if (!newTitle.equals(oldTitle)) {
final String fnewTitle = newTitle;
runOnUiThread(new Runnable() {
public void run()
{
setTitle(fnewTitle);
}
});
}
}
}
// Subclasses can override to provide a custom layout
protected View createLayout()
{
// Set up the view's layout.
LayoutArrangement arrangement = LayoutArrangement.DEFAULT;
String layoutFromIntent = getIntentString(TiC.INTENT_PROPERTY_LAYOUT, "");
if (layoutFromIntent.equals(TiC.LAYOUT_HORIZONTAL)) {
arrangement = LayoutArrangement.HORIZONTAL;
} else if (layoutFromIntent.equals(TiC.LAYOUT_VERTICAL)) {
arrangement = LayoutArrangement.VERTICAL;
}
// Create the root view to be used by the activity.
// - Set the layout's proxy to null for now. Will be set later via setWindowProxy().
// - Make it focusable so Android won't auto-focus on the first focusable child view in the window.
// This makes it match iOS' behavior where no child view has the focus when a window is opened.
TiCompositeLayout compositeLayout = new TiCompositeLayout(this, arrangement, null);
compositeLayout.setFocusable(true);
compositeLayout.setFocusableInTouchMode(true);
compositeLayout.setDescendantFocusability(TiCompositeLayout.FOCUS_BEFORE_DESCENDANTS);
return compositeLayout;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
if (!callbackDataByPermission.isEmpty()) {
handlePermissionRequestResult(requestCode, permissions, grantResults);
}
}
private void handlePermissionRequestResult(Integer requestCode, String[] permissions, int[] grantResults)
{
PermissionContextData cbd = callbackDataByPermission.get(requestCode);
if (cbd == null) {
return;
}
String deniedPermissions = "";
for (int i = 0; i < grantResults.length; ++i) {
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
if (deniedPermissions.isEmpty()) {
deniedPermissions = permissions[i];
} else {
deniedPermissions = deniedPermissions + ", " + permissions[i];
}
}
}
KrollDict response = new KrollDict();
if (deniedPermissions.isEmpty()) {
response.putCodeAndMessage(0, null);
} else {
response.putCodeAndMessage(-1, "Permission(s) denied: " + deniedPermissions);
}
KrollFunction callback = cbd.getCallback();
if (callback != null) {
KrollObject context = cbd.getContext();
if (context == null) {
Log.w(TAG, "Permission callback context object is null");
}
callback.callAsync(context, response);
} else {
Log.w(TAG, "Permission callback function has not been set");
}
}
/**
* register permission request result callback for activity
*
* @param requestCode request code (8 Bit) to associate callback with request
* @param callback callback function which receives a KrollDict with success,
* code, optional message and requestCode
* @param context KrollObject as required by async callback pattern
*/
public static void registerPermissionRequestCallback(Integer requestCode, KrollFunction callback,
KrollObject context)
{
if (callback != null && context != null) {
callbackDataByPermission.put(requestCode, new PermissionContextData(requestCode, callback, context));
}
}
protected void setFullscreen(boolean fullscreen)
{
if (fullscreen) {
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
}
}
// Subclasses can override to handle post-creation (but pre-message fire) logic
@SuppressWarnings("deprecation")
protected void windowCreated(Bundle savedInstanceState)
{
boolean fullscreen = getIntentBoolean(TiC.PROPERTY_FULLSCREEN, false);
boolean modal = getIntentBoolean(TiC.PROPERTY_MODAL, false);
int softInputMode = getIntentInt(TiC.PROPERTY_WINDOW_SOFT_INPUT_MODE, -1);
int windowFlags = getIntentInt(TiC.PROPERTY_WINDOW_FLAGS, 0);
boolean hasSoftInputMode = softInputMode != -1;
setFullscreen(fullscreen);
// Add additional window flags to better handle fullscreen support on devices with notches.
{
// Fetch flags.
int uiFlags = getWindow().getDecorView().getSystemUiVisibility();
int allWindowFlags = windowFlags | getWindow().getAttributes().flags;
// If status bar is to be hidden, then we must also set the translucent status bar flag
// or else devices with a notch will show a black bar where the status bar used to be.
boolean isHidingStatusBar = (allWindowFlags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
isHidingStatusBar |= (uiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
isHidingStatusBar |= (uiFlags & View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0;
if (isHidingStatusBar) {
windowFlags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
}
// If navigation bar is to be hidden, then we must also set its translucent flag
// or else devices with a notch will show a black bar where the navigation bar used to be.
if ((uiFlags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0) {
windowFlags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
}
}
// Always allow screen cutouts/notches (such as the camera) to overlap window.
// Note: This won't overlap window's inner contents unless we call setFitsSystemWindows(true) down below,
// which is only enabled when Titanium's "extendSafeArea" property is set true.
if (Build.VERSION.SDK_INT >= 28) {
WindowManager.LayoutParams params = getWindow().getAttributes();
params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
getWindow().setAttributes(params);
}
// Add the flags provided via property 'windowFlags'.
if (windowFlags > 0) {
getWindow().addFlags(windowFlags);
}
// Remove translucent StatusBar/NavigationBar flags if window is not set up to extend beneath them.
// Not doing so will cause window to stretch beneath them anyways, but will fail to render there.
if (this.layout.getFitsSystemWindows() && !(this instanceof TiLaunchActivity)) {
int mask = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
mask |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
if ((getWindow().getAttributes().flags & mask) != 0) {
String message = "You cannot use a translucent status bar or navigation bar unless you "
+ "set the window's '" + TiC.PROPERTY_EXTEND_SAFE_AREA + "' property to true.";
Log.w(TAG, message);
getWindow().clearFlags(mask);
}
}
// Update system UI flags with based on currently assigned translucency flags.
{
int systemUIFlags = 0;
int allWindowFlags = getWindow().getAttributes().flags;
if ((allWindowFlags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0) {
systemUIFlags |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
}
if ((allWindowFlags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) != 0) {
systemUIFlags |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
}
if (systemUIFlags != 0) {
systemUIFlags |= getWindow().getDecorView().getSystemUiVisibility();
getWindow().getDecorView().setSystemUiVisibility(systemUIFlags);
}
}
if (modal) {
if (Build.VERSION.SDK_INT < TiC.API_LEVEL_ICE_CREAM_SANDWICH) {
// This flag is deprecated in API 14. On ICS, the background is not blurred but straight black.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
}
}
if (hasSoftInputMode) {
Log.d(TAG, "windowSoftInputMode: " + softInputMode, Log.DEBUG_MODE);
getWindow().setSoftInputMode(softInputMode);
}
// If this activity was created by a Window/TabGroup proxy, then give it this activity's reference.
int windowId = getIntentInt(TiC.INTENT_PROPERTY_WINDOW_ID, TiActivityWindows.INVALID_WINDOW_ID);
if (windowId != TiActivityWindows.INVALID_WINDOW_ID) {
if (TiActivityWindows.hasWindow(windowId)) {
// Pass this activity to the proxy so that it can add views to it.
TiActivityWindows.windowCreated(this, windowId, savedInstanceState);
} else {
// This activity's assigned proxy was not found.
// This happens when proxy has been closed before activity was created. Destroy this activity.
finish();
}
}
}
// Record if user has set a content view manually from hyperloop code during require of app.js!
@Override
public void setContentView(View view)
{
overridenLayout = true;
super.setContentView(view);
}
@Override
public void setContentView(int layoutResID)
{
overridenLayout = true;
super.setContentView(layoutResID);
}
@Override
public void setContentView(View view, LayoutParams params)
{
overridenLayout = true;
super.setContentView(view, params);
}
@Override
protected void attachBaseContext(Context newBase)
{
super.attachBaseContext(TiLocaleManager.getLocalizedContext(newBase));
}
@Override
/**
* When the activity is created, this method adds it to the activity stack and
* fires a javascript 'create' event.
* @param savedInstanceState Bundle of saved data.
*/
protected void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "Activity " + this + " onCreate", Log.DEBUG_MODE);
this.inForeground = true;
this.launchIntent = getIntent();
this.safeAreaMonitor = new TiActivitySafeAreaMonitor(this);
TiApplication tiApp = getTiApp();
TiApplication.addToActivityStack(this);
// Increment the Titanium activity reference count. To be decremented in onDestroy() method.
// Titanium's JavaScript runtime is created when we have at least 1 activity and destroyed when we have 0.
KrollRuntime.incrementActivityRefCount();
// We must create activity proxy after incrementing the activity reference count above.
// This is because proxy needs the JS runtime to exist when created.
this.activityProxy = new ActivityProxy(this);
Intent intent = this.launchIntent;
if (intent != null) {
if (intent.hasExtra(TiC.INTENT_PROPERTY_MESSENGER)) {
messenger = (Messenger) intent.getParcelableExtra(TiC.INTENT_PROPERTY_MESSENGER);
msgActivityCreatedId = intent.getIntExtra(TiC.INTENT_PROPERTY_MSG_ACTIVITY_CREATED_ID, -1);
msgId = intent.getIntExtra(TiC.INTENT_PROPERTY_MSG_ID, -1);
}
if (intent.hasExtra(TiC.PROPERTY_WINDOW_PIXEL_FORMAT)) {
getWindow().setFormat(intent.getIntExtra(TiC.PROPERTY_WINDOW_PIXEL_FORMAT, PixelFormat.UNKNOWN));
}
}
// Doing this on every create in case the activity is externally created.
TiPlatformHelper.getInstance().intializeDisplayMetrics(this);
// Create the root content layout, if not done already.
if (layout == null) {
layout = createLayout();
}
// Extend window's view under screen insets, if requested.
boolean extendSafeArea = false;
if (intent != null) {
extendSafeArea = intent.getBooleanExtra(TiC.PROPERTY_EXTEND_SAFE_AREA, false);
}
layout.setFitsSystemWindows(!extendSafeArea);
// Enable/disable timer used to turn off the screen if idle.
if ((intent != null) && intent.hasExtra(TiC.PROPERTY_KEEP_SCREEN_ON)) {
boolean keepScreenOn = intent.getBooleanExtra(TiC.PROPERTY_KEEP_SCREEN_ON, layout.getKeepScreenOn());
layout.setKeepScreenOn(keepScreenOn);
}
// Set the theme of the activity before calling super.onCreate().
// On 2.3 devices, it does not work if the theme is set after super.onCreate.
int theme = getIntentInt(TiC.PROPERTY_THEME, -1);
if (theme != -1) {
this.setTheme(theme);
}
// Set ActionBar into split mode must be done before the decor view has been created
// we need to do this before calling super.onCreate()
if (intent != null && intent.hasExtra(TiC.PROPERTY_SPLIT_ACTIONBAR)) {
getWindow().setUiOptions(ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW);
}
// we only want to set the current activity for good in the resume state but we need it right now.
// save off the existing current activity, set ourselves to be the new current activity temporarily
// so we don't run into problems when we give the proxy the event
Activity tempCurrentActivity = tiApp.getCurrentActivity();
tiApp.setCurrentActivity(this, this);
// we need to set window features before calling onCreate
this.requestWindowFeature(Window.FEATURE_PROGRESS);
this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.requestWindowFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);
}
super.onCreate(savedInstanceState);
// If activity is using Google's default ActionBar, then the below will return an ActionBar style handler
// intended to be called by onConfigurationChanged() which will resize its title bar and font.
// Note: We need to do this since we override "configChanges" in the "AndroidManifest.xml".
// Default ActionBar height is typically 56dp for portrait and 48dp for landscape.
this.actionBarStyleHandler = TiActionBarStyleHandler.from(this);
// If Google's ActionBar is being used, then add it to the top inset height. (Exclude from safe-area.)
// Note: If a toolbar is passed to AppCompatActivity.setSupportActionBar(), then ActionBar is a wrapper
// around that toolbar under our content view and is included in the safe-area.
this.safeAreaMonitor.setActionBarAddedAsInset(this.actionBarStyleHandler != null);
// Start handling safe-area inset changes.
this.safeAreaMonitor.setOnChangedListener(new TiActivitySafeAreaMonitor.OnChangedListener() {
@Override
public void onChanged(TiActivitySafeAreaMonitor monitor)
{
TiWindowProxy windowProxy = TiBaseActivity.this.window;
if (windowProxy != null) {
windowProxy.fireSafeAreaChangedEvent();
}
}
});
this.safeAreaMonitor.start();
try {
windowCreated(savedInstanceState);
} catch (Throwable t) {
Thread.getDefaultUncaughtExceptionHandler().uncaughtException(null, t);
}
// set the current activity back to what it was originally
tiApp.setCurrentActivity(this, tempCurrentActivity);
// If user changed the layout during app.js load, keep that
if (!overridenLayout) {
super.setContentView(layout);
}
// Set the title of the activity after setContentView.
// On 2.3 devices, if the title is set before setContentView, the app will crash when a NoTitleBar theme is used.
updateTitle();
sendMessage(msgActivityCreatedId);
// for backwards compatibility
sendMessage(msgId);
// store off the original orientation for the activity set in the AndroidManifest.xml
// for later use
originalOrientationMode = getRequestedOrientation();
if (window != null) {
window.onWindowActivityCreated();
}
if (activityProxy != null) {
dispatchCallback(TiC.PROPERTY_ON_CREATE, null);
}
synchronized (lifecycleListeners.synchronizedList())
{
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, savedInstanceState, TiLifecycle.LIFECYCLE_ON_CREATE);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
setCustomActionBar();
}
private void setCustomActionBar()
{
if (activityProxy.hasProperty(TiC.PROPERTY_SUPPORT_TOOLBAR)) {
try {
this.setSupportActionBar(
((Toolbar) ((TiToolbarProxy) activityProxy.getProperty(TiC.PROPERTY_SUPPORT_TOOLBAR))
.getToolbarInstance()));
} catch (RuntimeException e) {
Log.e(
TAG,
"Attempting to use Toolbar as ActionBar without disabling the default ActionBar in the current theme.\n"
+ "You must set 'windowActionBar' to false in your current theme. Or use one of the following themes:\n"
+ " - Theme.Titanium\n - Theme.AppCompat.Translucent.NoTitleBar\n - Theme.AppCompat.NoTitleBar\n"
+ "Which have ActionBar disabled by default.");
TiApplication.terminateActivityStack();
finish();
}
}
}
/**
* Gets the intent that originally created and launched this activity.
* <p>
* This intent is assigned within this activity's onCreate() method.
* It is intended to be used to resume this activity via startActivity().
* <p>
* The returned intent will not change when onNewIntent() or setIntent() has been called. Those methods
* are typically called when tapping a notification or when a custom URL scheme has been invoked.
* The activity's getIntent() method will return the updated intent, if changed.
* @return The intent used to create/launch this activity.
*/
public Intent getLaunchIntent()
{
return this.launchIntent;
}
public int getOriginalOrientationMode()
{
return originalOrientationMode;
}
public boolean isInForeground()
{
return inForeground;
}
public boolean isDestroyed()
{
return onDestroyFired;
}
protected void sendMessage(final int msgId)
{
if (messenger == null || msgId == -1) {
return;
}
// fire an async message on this thread's queue
// so we don't block onCreate() from returning
TiMessenger.postOnMain(new Runnable() {
public void run()
{
handleSendMessage(msgId);
}
});
}
protected void handleSendMessage(int messageId)
{
try {
Message message = TiMessenger.getMainMessenger().getHandler().obtainMessage(messageId, this);
messenger.send(message);
} catch (RemoteException e) {
Log.e(TAG, "Unable to message creator. finishing.", e);
finish();
} catch (RuntimeException e) {
Log.e(TAG, "Unable to message creator. finishing.", e);
finish();
}
}
protected TiActivitySupportHelper getSupportHelper()
{
if (supportHelper == null) {
this.supportHelper = new TiActivitySupportHelper(this);
// Register the supportHelper so we can get it back when the activity is recovered from force-quitting.
supportHelperId = TiActivitySupportHelpers.addSupportHelper(supportHelper);
}
return supportHelper;
}
// Activity Support
public int getUniqueResultCode()
{
return getSupportHelper().getUniqueResultCode();
}
/**
* See TiActivitySupport.launchActivityForResult for more details.
*/
public void launchActivityForResult(Intent intent, int code, TiActivityResultHandler resultHandler)
{
getSupportHelper().launchActivityForResult(intent, code, resultHandler);
}
/**
* See TiActivitySupport.launchIntentSenderForResult for more details.
*/
public void launchIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask,
int flagsValues, int extraFlags, Bundle options,
TiActivityResultHandler resultHandler)
{
getSupportHelper().launchIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues,
extraFlags, options, resultHandler);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
synchronized (onActivityResultListeners.synchronizedList())
{
for (OnActivityResultEvent listener : onActivityResultListeners.nonNull()) {
try {
TiLifecycle.fireOnActivityResultEvent(this, listener, requestCode, resultCode, data);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching onActivityResult event: " + t.getMessage(), t);
}
}
}
getSupportHelper().onActivityResult(requestCode, resultCode, data);
}
@Override
public void onBackPressed()
{
// Notify all listener that the back button was pressed.
synchronized (interceptOnBackPressedListeners.synchronizedList())
{
for (interceptOnBackPressedEvent listener : interceptOnBackPressedListeners.nonNull()) {
try {
if (listener.interceptOnBackPressed()) {
return;
}
} catch (Throwable t) {
Log.e(TAG, "Error dispatching interceptOnBackPressed event: " + t.getMessage(), t);
}
}
}
// Let the window proxy handle the back event first, if configured.
if (this.window != null) {
boolean hasBackEventHandler = false;
// Fire an "androidback" event if a listener exists.
if (this.window.hasListeners(TiC.EVENT_ANDROID_BACK)) {
this.window.fireEvent(TiC.EVENT_ANDROID_BACK, null);
hasBackEventHandler = true;
}
// Invoke the "onBack" property's callback if assigned.
if (this.window.hasProperty(TiC.PROPERTY_ON_BACK) && (this.activityProxy != null)) {
Object value = this.window.getProperty(TiC.PROPERTY_ON_BACK);
if (value instanceof KrollFunction) {
KrollFunction onBackCallback = (KrollFunction) value;
onBackCallback.callAsync(activityProxy.getKrollObject(), new Object[] {});
hasBackEventHandler = true;
}
}
// Do not allow the system to handle back press if window proxy has an event handler.
// In this case, the JS code must explicity close() or finish() the activity window itself.
if (hasBackEventHandler) {
return;
}
}
// Handle app exit ourselves since the above window proxy did not handle the back event.
boolean exitOnClose = (TiActivityWindows.getWindowCount() <= 1);
if (this.window != null) {
exitOnClose = TiConvert.toBoolean(this.window.getProperty(TiC.PROPERTY_EXIT_ON_CLOSE), exitOnClose);
}
if (exitOnClose) {
// Destroy all remaining activitities, including root splash activity.
Log.d(TAG, "onBackPressed: exit");
finishAffinity();
TiApplication.terminateActivityStack();
return;
} else if (TiActivityWindows.getWindowCount() <= 1) {
// Don't destroy this activity if it's the last one left. Home-out instead.
Log.d(TAG, "onBackPressed: suspend to background");
moveTaskToBack(true);
return;
}
// Allow the system to finish/destroy this activity.
super.onBackPressed();
}
@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
boolean handled = false;
TiViewProxy window;
if (this.window != null) {
window = this.window;
} else {
window = this.view;
}
if (window == null) {
return super.dispatchKeyEvent(event);
}
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK: {
if (event.getAction() == KeyEvent.ACTION_UP) {
KrollProxy proxy = null;
//androidback could be fired from a tabGroup window (activityProxy)
//or hw window (window).This event is added specifically to the activity
//proxy of a tab group in window.js
if (activityProxy.hasListeners(TiC.EVENT_ANDROID_BACK)) {
proxy = activityProxy;
} else if (window.hasListeners(TiC.EVENT_ANDROID_BACK)) {