/
TiBaseActivity.java
1669 lines (1434 loc) Β· 49.4 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-2014 by Appcelerator, 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.CopyOnWriteArrayList;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
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.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.TiMenuSupport;
import org.appcelerator.titanium.util.TiPlatformHelper;
import org.appcelerator.titanium.util.TiUIHelper;
import org.appcelerator.titanium.util.TiWeakList;
import org.appcelerator.titanium.view.TiCompositeLayout;
import org.appcelerator.titanium.view.TiCompositeLayout.LayoutArrangement;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.app.Dialog;
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.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import com.appcelerator.analytics.APSAnalytics;
/**
* 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 static OrientationChangedListener orientationChangedListener = null;
private OrientationEventListener orientationListener;
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 APSAnalytics analytics = APSAnalytics.getInstance();
public static KrollObject storageCallbackContext, cameraCallbackContext, contactsCallbackContext, oldCalendarCallbackContext, calendarCallbackContext, locationCallbackContext;
public static KrollFunction storagePermissionCallback, cameraPermissionCallback, contactsPermissionCallback, oldCalendarPermissionCallback, calendarPermissionCallback, locationPermissionCallback;
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 int orientationDegrees;
protected TiMenuSupport menuHelper;
protected Messenger messenger;
protected int msgActivityCreatedId = -1;
protected int msgId = -1;
protected static int previousOrientation = -1;
//Storing the activity's dialogs and their persistence
private CopyOnWriteArrayList<DialogWrapper> dialogs = new CopyOnWriteArrayList<DialogWrapper>();
private Stack<TiWindowProxy> windowStack = new Stack<TiWindowProxy>();
public TiWindowProxy lwWindow;
public boolean isResumed = false;
private boolean overridenLayout;
public 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 void addWindowToStack(TiWindowProxy proxy)
{
if (windowStack.contains(proxy)) {
Log.e(TAG, "Window already exists in stack", Log.DEBUG_MODE);
return;
}
boolean isEmpty = windowStack.empty();
if (!isEmpty) {
windowStack.peek().onWindowFocusChange(false);
}
windowStack.add(proxy);
if (!isEmpty) {
proxy.onWindowFocusChange(true);
}
}
public void removeWindowFromStack(TiWindowProxy proxy)
{
proxy.onWindowFocusChange(false);
boolean isTopWindow = ( (!windowStack.isEmpty()) && (windowStack.peek() == proxy) ) ? true : false;
windowStack.remove(proxy);
//Fire focus only if activity is not paused and the removed window was topWindow
if (!windowStack.empty() && isResumed && isTopWindow) {
TiWindowProxy nextWindow = windowStack.peek();
nextWindow.onWindowFocusChange(true);
}
}
/**
* Returns the window at the top of the stack.
* @return the top window or null if the stack is empty.
*/
public TiWindowProxy topWindowOnStack()
{
return (windowStack.isEmpty()) ? null : windowStack.peek();
}
// could use a normal ConfigurationChangedListener but since only orientation changes are
// forwarded, create a separate interface in order to limit scope and maintain clarity
public static interface OrientationChangedListener
{
public void onOrientationChanged (int configOrientationMode, int width, int height);
}
public static void registerOrientationListener (OrientationChangedListener listener)
{
orientationChangedListener = listener;
}
public static void deregisterOrientationListener()
{
orientationChangedListener = null;
}
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 (!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);
}
public void registerOrientationChangedListener (OrientationChangedListener listener)
{
orientationChangedListener = listener;
}
public void deregisterOrientationChangedListener()
{
orientationChangedListener = null;
}
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()
{
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;
}
// set to null for now, this will get set correctly in setWindowProxy()
return new TiCompositeLayout(this, arrangement, null);
}
private void permissionCallback(int[] grantResults, KrollFunction callback, KrollObject context, String permission) {
if (callback == null) {
return;
}
boolean granted = true;
for (int i = 0; i < grantResults.length; ++i) {
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
granted = false;
break;
}
}
if (granted) {
KrollDict response = new KrollDict();
response.putCodeAndMessage(0, null);
callback.callAsync(context, response);
} else {
KrollDict response = new KrollDict();
response.putCodeAndMessage(-1, "One or more permission(s) were denied");
callback.callAsync(context, response);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case TiC.PERMISSION_CODE_CAMERA: {
permissionCallback(grantResults, cameraPermissionCallback, cameraCallbackContext, "Camera");
return;
}
case TiC.PERMISSION_CODE_OLD_CALENDAR: {
permissionCallback(grantResults, oldCalendarPermissionCallback, oldCalendarCallbackContext, "Calendar");
return;
}
case TiC.PERMISSION_CODE_CALENDAR: {
permissionCallback(grantResults, calendarPermissionCallback, calendarCallbackContext, "Calendar");
return;
}
case TiC.PERMISSION_CODE_LOCATION: {
permissionCallback(grantResults, locationPermissionCallback, locationCallbackContext, "Location");
return;
}
case TiC.PERMISSION_CODE_CONTACTS: {
permissionCallback(grantResults, contactsPermissionCallback, contactsCallbackContext, "Contacts");
return;
}
case TiC.PERMISSION_CODE_EXTERNAL_STORAGE: {
permissionCallback(grantResults, storagePermissionCallback, storageCallbackContext, "Storage");
return;
}
}
}
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);
if (windowFlags > 0) {
getWindow().addFlags(windowFlags);
}
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);
}
boolean useActivityWindow = getIntentBoolean(TiC.INTENT_PROPERTY_USE_ACTIVITY_WINDOW, false);
if (useActivityWindow) {
int windowId = getIntentInt(TiC.INTENT_PROPERTY_WINDOW_ID, -1);
TiActivityWindows.windowCreated(this, windowId, savedInstanceState);
}
}
// 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
/**
* 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);
inForeground = true;
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
super.onCreate(savedInstanceState);
if (!isFinishing()) {
finish();
}
return;
}
// If all the activities has been killed and the runtime has been disposed or the app's hosting process has
// been killed, we cannot recover one specific activity because the info of the top-most view proxy has been
// lost (TiActivityWindows.dispose()). In this case, we have to restart the app.
if (TiBaseActivity.isUnsupportedReLaunch(this, savedInstanceState)) {
Log.w(TAG, "Runtime has been disposed or app has been killed. Finishing.");
super.onCreate(savedInstanceState);
tiApp.scheduleRestart(250);
finish();
return;
}
TiApplication.addToActivityStack(this);
// create the activity proxy here so that it is accessible from the activity in all cases
activityProxy = new ActivityProxy(this);
// Increment the reference count so we correctly clean up when all of our activities have been destroyed
KrollRuntime.incrementActivityRefCount();
Intent intent = getIntent();
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);
if (layout == null) {
layout = createLayout();
}
if (intent != null && intent.hasExtra(TiC.PROPERTY_KEEP_SCREEN_ON)) {
layout.setKeepScreenOn(intent.getBooleanExtra(TiC.PROPERTY_KEEP_SCREEN_ON, layout.getKeepScreenOn()));
}
// 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);
windowCreated(savedInstanceState);
if (activityProxy != null) {
dispatchCallback(TiC.PROPERTY_ON_CREATE, null);
activityProxy.fireEvent(TiC.EVENT_CREATE, null);
}
// 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) {
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();
orientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
@Override
public void onOrientationChanged(int orientation) {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int rotation = getWindowManager().getDefaultDisplay().getRotation();
if ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270)
&& rotation != previousOrientation) {
callOrientationChangedListener(TiApplication.getAppRootOrCurrentActivity(), width, height, rotation);
} else if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180)
&& rotation != previousOrientation) {
callOrientationChangedListener(TiApplication.getAppRootOrCurrentActivity(), width, height, rotation);
}
}
};
if (orientationListener.canDetectOrientation() == true) {
orientationListener.enable();
} else {
Log.w(TAG, "Cannot detect orientation");
orientationListener.disable();
}
if (window != null) {
window.onWindowActivityCreated();
}
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);
}
}
}
}
public int getOriginalOrientationMode()
{
return originalOrientationMode;
}
public boolean isInForeground()
{
return inForeground;
}
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()
{
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);
}
}
}
TiWindowProxy topWindow = topWindowOnStack();
// Prevent default Android behavior for "back" press
// if the top window has a listener to handle the event.
if (topWindow != null && topWindow.hasListeners(TiC.EVENT_ANDROID_BACK)) {
topWindow.fireEvent(TiC.EVENT_ANDROID_BACK, null);
} else {
// If event is not handled by any listeners allow default behavior.
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) {
String backEvent = "android:back";
KrollProxy proxy = null;
//android:back 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(backEvent)) {
proxy = activityProxy;
} else if (window.hasListeners(backEvent)) {
proxy = window;
}
if (proxy != null) {
proxy.fireEvent(backEvent, null);
handled = true;
}
}
break;
}
case KeyEvent.KEYCODE_CAMERA : {
if (window.hasListeners(TiC.EVENT_ANDROID_CAMERA)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_CAMERA, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:camera")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:camera", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_FOCUS : {
if (window.hasListeners(TiC.EVENT_ANDROID_FOCUS)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_FOCUS, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:focus")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:focus", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_SEARCH : {
if (window.hasListeners(TiC.EVENT_ANDROID_SEARCH)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_SEARCH, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:search")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:search", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_UP : {
if (window.hasListeners(TiC.EVENT_ANDROID_VOLUP)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_VOLUP, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:volup")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:volup", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_DOWN : {
if (window.hasListeners(TiC.EVENT_ANDROID_VOLDOWN)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_VOLDOWN, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:voldown")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:voldown", null);
}
handled = true;
}
break;
}
}
if (!handled) {
handled = super.dispatchKeyEvent(event);
}
return handled;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// If targetSdkVersion is set to 11+, Android will invoke this function
// to initialize the menu (since it's part of the action bar). Due
// to the fix for Android bug 2373, activityProxy won't be initialized b/c the
// activity is expected to restart, so we will ignore it.
if (activityProxy == null) {
return false;
}
boolean listenerExists = false;
synchronized (onCreateOptionsMenuListeners.synchronizedList()) {
for (OnCreateOptionsMenuEvent listener : onCreateOptionsMenuListeners.nonNull()) {
try {
listenerExists = true;
TiLifecycle.fireOnCreateOptionsMenuEvent(this, listener, menu);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching OnCreateOptionsMenuEvent: " + t.getMessage(), t);
}
}
}
if (menuHelper == null) {
menuHelper = new TiMenuSupport(activityProxy);
}
return menuHelper.onCreateOptionsMenu(super.onCreateOptionsMenu(menu) || listenerExists, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case android.R.id.home:
if (activityProxy != null) {
ActionBarProxy actionBarProxy = activityProxy.getActionBar();
if (actionBarProxy != null) {
KrollFunction onHomeIconItemSelected = (KrollFunction) actionBarProxy
.getProperty(TiC.PROPERTY_ON_HOME_ICON_ITEM_SELECTED);
KrollDict event = new KrollDict();
event.put(TiC.EVENT_PROPERTY_SOURCE, actionBarProxy);