-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathActivity.java
6648 lines (6242 loc) · 274 KB
/
Activity.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
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.app;
import android.annotation.CallSuper;
import android.annotation.DrawableRes;
import android.annotation.IdRes;
import android.annotation.IntDef;
import android.annotation.LayoutRes;
import android.annotation.MainThread;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StyleRes;
import android.os.PersistableBundle;
import android.transition.Scene;
import android.transition.TransitionManager;
import android.util.ArrayMap;
import android.util.SuperNotCalledException;
import android.widget.Toolbar;
import com.android.internal.app.IVoiceInteractor;
import com.android.internal.app.WindowDecorActionBar;
import com.android.internal.app.ToolbarActionBar;
import android.annotation.SystemApi;
import android.app.admin.DevicePolicyManager;
import android.app.assist.AssistContent;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.IIntentSender;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.session.MediaController;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Parcelable;
import android.os.RemoteException;
import android.os.StrictMode;
import android.os.UserHandle;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.TextKeyListener;
import android.util.AttributeSet;
import android.util.EventLog;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Slog;
import android.util.SparseArray;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import com.android.internal.policy.PhoneWindow;
import android.view.SearchEvent;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewManager;
import android.view.ViewRootImpl;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManagerGlobal;
import android.view.accessibility.AccessibilityEvent;
import android.widget.AdapterView;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* An activity is a single, focused thing that the user can do. Almost all
* activities interact with the user, so the Activity class takes care of
* creating a window for you in which you can place your UI with
* {@link #setContentView}. While activities are often presented to the user
* as full-screen windows, they can also be used in other ways: as floating
* windows (via a theme with {@link android.R.attr#windowIsFloating} set)
* or embedded inside of another activity (using {@link ActivityGroup}).
*
* There are two methods almost all subclasses of Activity will implement:
*
* <ul>
* <li> {@link #onCreate} is where you initialize your activity. Most
* importantly, here you will usually call {@link #setContentView(int)}
* with a layout resource defining your UI, and using {@link #findViewById}
* to retrieve the widgets in that UI that you need to interact with
* programmatically.
*
* <li> {@link #onPause} is where you deal with the user leaving your
* activity. Most importantly, any changes made by the user should at this
* point be committed (usually to the
* {@link android.content.ContentProvider} holding the data).
* </ul>
*
* <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
* activity classes must have a corresponding
* {@link android.R.styleable#AndroidManifestActivity <activity>}
* declaration in their package's <code>AndroidManifest.xml</code>.</p>
*
* <p>Topics covered here:
* <ol>
* <li><a href="#Fragments">Fragments</a>
* <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
* <li><a href="#ConfigurationChanges">Configuration Changes</a>
* <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
* <li><a href="#SavingPersistentState">Saving Persistent State</a>
* <li><a href="#Permissions">Permissions</a>
* <li><a href="#ProcessLifecycle">Process Lifecycle</a>
* </ol>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>The Activity class is an important part of an application's overall lifecycle,
* and the way activities are launched and put together is a fundamental
* part of the platform's application model. For a detailed perspective on the structure of an
* Android application and how activities behave, please read the
* <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
* <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
* developer guides.</p>
*
* <p>You can also find a detailed discussion about how to create activities in the
* <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>
* developer guide.</p>
* </div>
*
* <a name="Fragments"></a>
* <h3>Fragments</h3>
*
* <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
* implementations can make use of the {@link Fragment} class to better
* modularize their code, build more sophisticated user interfaces for larger
* screens, and help scale their application between small and large screens.
*
* <a name="ActivityLifecycle"></a>
* <h3>Activity Lifecycle</h3>
*
* <p>Activities in the system are managed as an <em>activity stack</em>.
* When a new activity is started, it is placed on the top of the stack
* and becomes the running activity -- the previous activity always remains
* below it in the stack, and will not come to the foreground again until
* the new activity exits.</p>
*
* <p>An activity has essentially four states:</p>
* <ul>
* <li> If an activity in the foreground of the screen (at the top of
* the stack),
* it is <em>active</em> or <em>running</em>. </li>
* <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
* or transparent activity has focus on top of your activity), it
* is <em>paused</em>. A paused activity is completely alive (it
* maintains all state and member information and remains attached to
* the window manager), but can be killed by the system in extreme
* low memory situations.
* <li>If an activity is completely obscured by another activity,
* it is <em>stopped</em>. It still retains all state and member information,
* however, it is no longer visible to the user so its window is hidden
* and it will often be killed by the system when memory is needed
* elsewhere.</li>
* <li>If an activity is paused or stopped, the system can drop the activity
* from memory by either asking it to finish, or simply killing its
* process. When it is displayed again to the user, it must be
* completely restarted and restored to its previous state.</li>
* </ul>
*
* <p>The following diagram shows the important state paths of an Activity.
* The square rectangles represent callback methods you can implement to
* perform operations when the Activity moves between states. The colored
* ovals are major states the Activity can be in.</p>
*
* <p><img src="../../../images/activity_lifecycle.png"
* alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
*
* <p>There are three key loops you may be interested in monitoring within your
* activity:
*
* <ul>
* <li>The <b>entire lifetime</b> of an activity happens between the first call
* to {@link android.app.Activity#onCreate} through to a single final call
* to {@link android.app.Activity#onDestroy}. An activity will do all setup
* of "global" state in onCreate(), and release all remaining resources in
* onDestroy(). For example, if it has a thread running in the background
* to download data from the network, it may create that thread in onCreate()
* and then stop the thread in onDestroy().
*
* <li>The <b>visible lifetime</b> of an activity happens between a call to
* {@link android.app.Activity#onStart} until a corresponding call to
* {@link android.app.Activity#onStop}. During this time the user can see the
* activity on-screen, though it may not be in the foreground and interacting
* with the user. Between these two methods you can maintain resources that
* are needed to show the activity to the user. For example, you can register
* a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
* that impact your UI, and unregister it in onStop() when the user no
* longer sees what you are displaying. The onStart() and onStop() methods
* can be called multiple times, as the activity becomes visible and hidden
* to the user.
*
* <li>The <b>foreground lifetime</b> of an activity happens between a call to
* {@link android.app.Activity#onResume} until a corresponding call to
* {@link android.app.Activity#onPause}. During this time the activity is
* in front of all other activities and interacting with the user. An activity
* can frequently go between the resumed and paused states -- for example when
* the device goes to sleep, when an activity result is delivered, when a new
* intent is delivered -- so the code in these methods should be fairly
* lightweight.
* </ul>
*
* <p>The entire lifecycle of an activity is defined by the following
* Activity methods. All of these are hooks that you can override
* to do appropriate work when the activity changes state. All
* activities will implement {@link android.app.Activity#onCreate}
* to do their initial setup; many will also implement
* {@link android.app.Activity#onPause} to commit changes to data and
* otherwise prepare to stop interacting with the user. You should always
* call up to your superclass when implementing these methods.</p>
*
* </p>
* <pre class="prettyprint">
* public class Activity extends ApplicationContext {
* protected void onCreate(Bundle savedInstanceState);
*
* protected void onStart();
*
* protected void onRestart();
*
* protected void onResume();
*
* protected void onPause();
*
* protected void onStop();
*
* protected void onDestroy();
* }
* </pre>
*
* <p>In general the movement through an activity's lifecycle looks like
* this:</p>
*
* <table border="2" width="85%" align="center" frame="hsides" rules="rows">
* <colgroup align="left" span="3" />
* <colgroup align="left" />
* <colgroup align="center" />
* <colgroup align="center" />
*
* <thead>
* <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
* </thead>
*
* <tbody>
* <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
* <td>Called when the activity is first created.
* This is where you should do all of your normal static set up:
* create views, bind data to lists, etc. This method also
* provides you with a Bundle containing the activity's previously
* frozen state, if there was one.
* <p>Always followed by <code>onStart()</code>.</td>
* <td align="center">No</td>
* <td align="center"><code>onStart()</code></td>
* </tr>
*
* <tr><td rowspan="5" style="border-left: none; border-right: none;"> </td>
* <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
* <td>Called after your activity has been stopped, prior to it being
* started again.
* <p>Always followed by <code>onStart()</code></td>
* <td align="center">No</td>
* <td align="center"><code>onStart()</code></td>
* </tr>
*
* <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
* <td>Called when the activity is becoming visible to the user.
* <p>Followed by <code>onResume()</code> if the activity comes
* to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
* <td align="center">No</td>
* <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
* </tr>
*
* <tr><td rowspan="2" style="border-left: none;"> </td>
* <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
* <td>Called when the activity will start
* interacting with the user. At this point your activity is at
* the top of the activity stack, with user input going to it.
* <p>Always followed by <code>onPause()</code>.</td>
* <td align="center">No</td>
* <td align="center"><code>onPause()</code></td>
* </tr>
*
* <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
* <td>Called when the system is about to start resuming a previous
* activity. This is typically used to commit unsaved changes to
* persistent data, stop animations and other things that may be consuming
* CPU, etc. Implementations of this method must be very quick because
* the next activity will not be resumed until this method returns.
* <p>Followed by either <code>onResume()</code> if the activity
* returns back to the front, or <code>onStop()</code> if it becomes
* invisible to the user.</td>
* <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
* <td align="center"><code>onResume()</code> or<br>
* <code>onStop()</code></td>
* </tr>
*
* <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
* <td>Called when the activity is no longer visible to the user, because
* another activity has been resumed and is covering this one. This
* may happen either because a new activity is being started, an existing
* one is being brought in front of this one, or this one is being
* destroyed.
* <p>Followed by either <code>onRestart()</code> if
* this activity is coming back to interact with the user, or
* <code>onDestroy()</code> if this activity is going away.</td>
* <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
* <td align="center"><code>onRestart()</code> or<br>
* <code>onDestroy()</code></td>
* </tr>
*
* <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
* <td>The final call you receive before your
* activity is destroyed. This can happen either because the
* activity is finishing (someone called {@link Activity#finish} on
* it, or because the system is temporarily destroying this
* instance of the activity to save space. You can distinguish
* between these two scenarios with the {@link
* Activity#isFinishing} method.</td>
* <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
* <td align="center"><em>nothing</em></td>
* </tr>
* </tbody>
* </table>
*
* <p>Note the "Killable" column in the above table -- for those methods that
* are marked as being killable, after that method returns the process hosting the
* activity may be killed by the system <em>at any time</em> without another line
* of its code being executed. Because of this, you should use the
* {@link #onPause} method to write any persistent data (such as user edits)
* to storage. In addition, the method
* {@link #onSaveInstanceState(Bundle)} is called before placing the activity
* in such a background state, allowing you to save away any dynamic instance
* state in your activity into the given Bundle, to be later received in
* {@link #onCreate} if the activity needs to be re-created.
* See the <a href="#ProcessLifecycle">Process Lifecycle</a>
* section for more information on how the lifecycle of a process is tied
* to the activities it is hosting. Note that it is important to save
* persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
* because the latter is not part of the lifecycle callbacks, so will not
* be called in every situation as described in its documentation.</p>
*
* <p class="note">Be aware that these semantics will change slightly between
* applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
* vs. those targeting prior platforms. Starting with Honeycomb, an application
* is not in the killable state until its {@link #onStop} has returned. This
* impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
* safely called after {@link #onPause()} and allows and application to safely
* wait until {@link #onStop()} to save persistent state.</p>
*
* <p>For those methods that are not marked as being killable, the activity's
* process will not be killed by the system starting from the time the method
* is called and continuing after it returns. Thus an activity is in the killable
* state, for example, between after <code>onPause()</code> to the start of
* <code>onResume()</code>.</p>
*
* <a name="ConfigurationChanges"></a>
* <h3>Configuration Changes</h3>
*
* <p>If the configuration of the device (as defined by the
* {@link Configuration Resources.Configuration} class) changes,
* then anything displaying a user interface will need to update to match that
* configuration. Because Activity is the primary mechanism for interacting
* with the user, it includes special support for handling configuration
* changes.</p>
*
* <p>Unless you specify otherwise, a configuration change (such as a change
* in screen orientation, language, input devices, etc) will cause your
* current activity to be <em>destroyed</em>, going through the normal activity
* lifecycle process of {@link #onPause},
* {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
* had been in the foreground or visible to the user, once {@link #onDestroy} is
* called in that instance then a new instance of the activity will be
* created, with whatever savedInstanceState the previous instance had generated
* from {@link #onSaveInstanceState}.</p>
*
* <p>This is done because any application resource,
* including layout files, can change based on any configuration value. Thus
* the only safe way to handle a configuration change is to re-retrieve all
* resources, including layouts, drawables, and strings. Because activities
* must already know how to save their state and re-create themselves from
* that state, this is a convenient way to have an activity restart itself
* with a new configuration.</p>
*
* <p>In some special cases, you may want to bypass restarting of your
* activity based on one or more types of configuration changes. This is
* done with the {@link android.R.attr#configChanges android:configChanges}
* attribute in its manifest. For any types of configuration changes you say
* that you handle there, you will receive a call to your current activity's
* {@link #onConfigurationChanged} method instead of being restarted. If
* a configuration change involves any that you do not handle, however, the
* activity will still be restarted and {@link #onConfigurationChanged}
* will not be called.</p>
*
* <a name="StartingActivities"></a>
* <h3>Starting Activities and Getting Results</h3>
*
* <p>The {@link android.app.Activity#startActivity}
* method is used to start a
* new activity, which will be placed at the top of the activity stack. It
* takes a single argument, an {@link android.content.Intent Intent},
* which describes the activity
* to be executed.</p>
*
* <p>Sometimes you want to get a result back from an activity when it
* ends. For example, you may start an activity that lets the user pick
* a person in a list of contacts; when it ends, it returns the person
* that was selected. To do this, you call the
* {@link android.app.Activity#startActivityForResult(Intent, int)}
* version with a second integer parameter identifying the call. The result
* will come back through your {@link android.app.Activity#onActivityResult}
* method.</p>
*
* <p>When an activity exits, it can call
* {@link android.app.Activity#setResult(int)}
* to return data back to its parent. It must always supply a result code,
* which can be the standard results RESULT_CANCELED, RESULT_OK, or any
* custom values starting at RESULT_FIRST_USER. In addition, it can optionally
* return back an Intent containing any additional data it wants. All of this
* information appears back on the
* parent's <code>Activity.onActivityResult()</code>, along with the integer
* identifier it originally supplied.</p>
*
* <p>If a child activity fails for any reason (such as crashing), the parent
* activity will receive a result with the code RESULT_CANCELED.</p>
*
* <pre class="prettyprint">
* public class MyActivity extends Activity {
* ...
*
* static final int PICK_CONTACT_REQUEST = 0;
*
* public boolean onKeyDown(int keyCode, KeyEvent event) {
* if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
* // When the user center presses, let them pick a contact.
* startActivityForResult(
* new Intent(Intent.ACTION_PICK,
* new Uri("content://contacts")),
* PICK_CONTACT_REQUEST);
* return true;
* }
* return false;
* }
*
* protected void onActivityResult(int requestCode, int resultCode,
* Intent data) {
* if (requestCode == PICK_CONTACT_REQUEST) {
* if (resultCode == RESULT_OK) {
* // A contact was picked. Here we will just display it
* // to the user.
* startActivity(new Intent(Intent.ACTION_VIEW, data));
* }
* }
* }
* }
* </pre>
*
* <a name="SavingPersistentState"></a>
* <h3>Saving Persistent State</h3>
*
* <p>There are generally two kinds of persistent state than an activity
* will deal with: shared document-like data (typically stored in a SQLite
* database using a {@linkplain android.content.ContentProvider content provider})
* and internal state such as user preferences.</p>
*
* <p>For content provider data, we suggest that activities use a
* "edit in place" user model. That is, any edits a user makes are effectively
* made immediately without requiring an additional confirmation step.
* Supporting this model is generally a simple matter of following two rules:</p>
*
* <ul>
* <li> <p>When creating a new document, the backing database entry or file for
* it is created immediately. For example, if the user chooses to write
* a new e-mail, a new entry for that e-mail is created as soon as they
* start entering data, so that if they go to any other activity after
* that point this e-mail will now appear in the list of drafts.</p>
* <li> <p>When an activity's <code>onPause()</code> method is called, it should
* commit to the backing content provider or file any changes the user
* has made. This ensures that those changes will be seen by any other
* activity that is about to run. You will probably want to commit
* your data even more aggressively at key times during your
* activity's lifecycle: for example before starting a new
* activity, before finishing your own activity, when the user
* switches between input fields, etc.</p>
* </ul>
*
* <p>This model is designed to prevent data loss when a user is navigating
* between activities, and allows the system to safely kill an activity (because
* system resources are needed somewhere else) at any time after it has been
* paused. Note this implies
* that the user pressing BACK from your activity does <em>not</em>
* mean "cancel" -- it means to leave the activity with its current contents
* saved away. Canceling edits in an activity must be provided through
* some other mechanism, such as an explicit "revert" or "undo" option.</p>
*
* <p>See the {@linkplain android.content.ContentProvider content package} for
* more information about content providers. These are a key aspect of how
* different activities invoke and propagate data between themselves.</p>
*
* <p>The Activity class also provides an API for managing internal persistent state
* associated with an activity. This can be used, for example, to remember
* the user's preferred initial display in a calendar (day view or week view)
* or the user's default home page in a web browser.</p>
*
* <p>Activity persistent state is managed
* with the method {@link #getPreferences},
* allowing you to retrieve and
* modify a set of name/value pairs associated with the activity. To use
* preferences that are shared across multiple application components
* (activities, receivers, services, providers), you can use the underlying
* {@link Context#getSharedPreferences Context.getSharedPreferences()} method
* to retrieve a preferences
* object stored under a specific name.
* (Note that it is not possible to share settings data across application
* packages -- for that you will need a content provider.)</p>
*
* <p>Here is an excerpt from a calendar activity that stores the user's
* preferred view mode in its persistent settings:</p>
*
* <pre class="prettyprint">
* public class CalendarActivity extends Activity {
* ...
*
* static final int DAY_VIEW_MODE = 0;
* static final int WEEK_VIEW_MODE = 1;
*
* private SharedPreferences mPrefs;
* private int mCurViewMode;
*
* protected void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
*
* SharedPreferences mPrefs = getSharedPreferences();
* mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
* }
*
* protected void onPause() {
* super.onPause();
*
* SharedPreferences.Editor ed = mPrefs.edit();
* ed.putInt("view_mode", mCurViewMode);
* ed.commit();
* }
* }
* </pre>
*
* <a name="Permissions"></a>
* <h3>Permissions</h3>
*
* <p>The ability to start a particular Activity can be enforced when it is
* declared in its
* manifest's {@link android.R.styleable#AndroidManifestActivity <activity>}
* tag. By doing so, other applications will need to declare a corresponding
* {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>}
* element in their own manifest to be able to start that activity.
*
* <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
* Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
* Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
* Activity access to the specific URIs in the Intent. Access will remain
* until the Activity has finished (it will remain across the hosting
* process being killed and other temporary destruction). As of
* {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
* was already created and a new Intent is being delivered to
* {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
* to the existing ones it holds.
*
* <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
* document for more information on permissions and security in general.
*
* <a name="ProcessLifecycle"></a>
* <h3>Process Lifecycle</h3>
*
* <p>The Android system attempts to keep application process around for as
* long as possible, but eventually will need to remove old processes when
* memory runs low. As described in <a href="#ActivityLifecycle">Activity
* Lifecycle</a>, the decision about which process to remove is intimately
* tied to the state of the user's interaction with it. In general, there
* are four states a process can be in based on the activities running in it,
* listed here in order of importance. The system will kill less important
* processes (the last ones) before it resorts to killing more important
* processes (the first ones).
*
* <ol>
* <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
* that the user is currently interacting with) is considered the most important.
* Its process will only be killed as a last resort, if it uses more memory
* than is available on the device. Generally at this point the device has
* reached a memory paging state, so this is required in order to keep the user
* interface responsive.
* <li> <p>A <b>visible activity</b> (an activity that is visible to the user
* but not in the foreground, such as one sitting behind a foreground dialog)
* is considered extremely important and will not be killed unless that is
* required to keep the foreground activity running.
* <li> <p>A <b>background activity</b> (an activity that is not visible to
* the user and has been paused) is no longer critical, so the system may
* safely kill its process to reclaim memory for other foreground or
* visible processes. If its process needs to be killed, when the user navigates
* back to the activity (making it visible on the screen again), its
* {@link #onCreate} method will be called with the savedInstanceState it had previously
* supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
* state as the user last left it.
* <li> <p>An <b>empty process</b> is one hosting no activities or other
* application components (such as {@link Service} or
* {@link android.content.BroadcastReceiver} classes). These are killed very
* quickly by the system as memory becomes low. For this reason, any
* background operation you do outside of an activity must be executed in the
* context of an activity BroadcastReceiver or Service to ensure that the system
* knows it needs to keep your process around.
* </ol>
*
* <p>Sometimes an Activity may need to do a long-running operation that exists
* independently of the activity lifecycle itself. An example may be a camera
* application that allows you to upload a picture to a web site. The upload
* may take a long time, and the application should allow the user to leave
* the application will it is executing. To accomplish this, your Activity
* should start a {@link Service} in which the upload takes place. This allows
* the system to properly prioritize your process (considering it to be more
* important than other non-visible applications) for the duration of the
* upload, independent of whether the original activity is paused, stopped,
* or finished.
*/
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback {
private static final String TAG = "Activity";
private static final boolean DEBUG_LIFECYCLE = false;
/** Standard activity result: operation canceled. */
public static final int RESULT_CANCELED = 0;
/** Standard activity result: operation succeeded. */
public static final int RESULT_OK = -1;
/** Start of user-defined activity results. */
public static final int RESULT_FIRST_USER = 1;
static final String FRAGMENTS_TAG = "android:fragments";
private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
private static class ManagedDialog {
Dialog mDialog;
Bundle mArgs;
}
private SparseArray<ManagedDialog> mManagedDialogs;
// set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
private Instrumentation mInstrumentation;
private IBinder mToken;
private int mIdent;
/*package*/ String mEmbeddedID;
private Application mApplication;
/*package*/ Intent mIntent;
/*package*/ String mReferrer;
private ComponentName mComponent;
/*package*/ ActivityInfo mActivityInfo;
/*package*/ ActivityThread mMainThread;
Activity mParent;
boolean mCalled;
/*package*/ boolean mResumed;
private boolean mStopped;
boolean mFinished;
boolean mStartedActivity;
private boolean mDestroyed;
private boolean mDoReportFullyDrawn = true;
/** true if the activity is going through a transient pause */
/*package*/ boolean mTemporaryPause = false;
/** true if the activity is being destroyed in order to recreate it with a new configuration */
/*package*/ boolean mChangingConfigurations = false;
/*package*/ int mConfigChangeFlags;
/*package*/ Configuration mCurrentConfig;
private SearchManager mSearchManager;
private MenuInflater mMenuInflater;
static final class NonConfigurationInstances {
Object activity;
HashMap<String, Object> children;
List<Fragment> fragments;
ArrayMap<String, LoaderManager> loaders;
VoiceInteractor voiceInteractor;
}
/* package */ NonConfigurationInstances mLastNonConfigurationInstances;
private Window mWindow;
private WindowManager mWindowManager;
/*package*/ View mDecor = null;
/*package*/ boolean mWindowAdded = false;
/*package*/ boolean mVisibleFromServer = false;
/*package*/ boolean mVisibleFromClient = true;
/*package*/ ActionBar mActionBar = null;
private boolean mEnableDefaultActionBarUp;
private VoiceInteractor mVoiceInteractor;
private CharSequence mTitle;
private int mTitleColor = 0;
// we must have a handler before the FragmentController is constructed
final Handler mHandler = new Handler();
final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
// Most recent call to requestVisibleBehind().
boolean mVisibleBehind;
private static final class ManagedCursor {
ManagedCursor(Cursor cursor) {
mCursor = cursor;
mReleased = false;
mUpdated = false;
}
private final Cursor mCursor;
private boolean mReleased;
private boolean mUpdated;
}
private final ArrayList<ManagedCursor> mManagedCursors =
new ArrayList<ManagedCursor>();
// protected by synchronized (this)
int mResultCode = RESULT_CANCELED;
Intent mResultData = null;
private TranslucentConversionListener mTranslucentCallback;
private boolean mChangeCanvasToTranslucent;
private SearchEvent mSearchEvent;
private boolean mTitleReady = false;
private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
private SpannableStringBuilder mDefaultKeySsb = null;
protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
@SuppressWarnings("unused")
private final Object mInstanceTracker = StrictMode.trackActivity(this);
private Thread mUiThread;
ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
/** Return the intent that started this activity. */
public Intent getIntent() {
return mIntent;
}
/**
* Change the intent returned by {@link #getIntent}. This holds a
* reference to the given intent; it does not copy it. Often used in
* conjunction with {@link #onNewIntent}.
*
* @param newIntent The new Intent object to return from getIntent
*
* @see #getIntent
* @see #onNewIntent
*/
public void setIntent(Intent newIntent) {
mIntent = newIntent;
}
/** Return the application that owns this activity. */
public final Application getApplication() {
return mApplication;
}
/** Is this activity embedded inside of another activity? */
public final boolean isChild() {
return mParent != null;
}
/** Return the parent activity if this view is an embedded child. */
public final Activity getParent() {
return mParent;
}
/** Retrieve the window manager for showing custom windows. */
public WindowManager getWindowManager() {
return mWindowManager;
}
/**
* Retrieve the current {@link android.view.Window} for the activity.
* This can be used to directly access parts of the Window API that
* are not available through Activity/Screen.
*
* @return Window The current window, or null if the activity is not
* visual.
*/
public Window getWindow() {
return mWindow;
}
/**
* Return the LoaderManager for this activity, creating it if needed.
*/
public LoaderManager getLoaderManager() {
return mFragments.getLoaderManager();
}
/**
* Calls {@link android.view.Window#getCurrentFocus} on the
* Window of this Activity to return the currently focused view.
*
* @return View The current View with focus or null.
*
* @see #getWindow
* @see android.view.Window#getCurrentFocus
*/
@Nullable
public View getCurrentFocus() {
return mWindow != null ? mWindow.getCurrentFocus() : null;
}
/**
* Called when the activity is starting. This is where most initialization
* should go: calling {@link #setContentView(int)} to inflate the
* activity's UI, using {@link #findViewById} to programmatically interact
* with widgets in the UI, calling
* {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
* cursors for data being displayed, etc.
*
* <p>You can call {@link #finish} from within this function, in
* which case onDestroy() will be immediately called without any of the rest
* of the activity lifecycle ({@link #onStart}, {@link #onResume},
* {@link #onPause}, etc) executing.
*
* <p><em>Derived classes must call through to the super class's
* implementation of this method. If they do not, an exception will be
* thrown.</em></p>
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
*
* @see #onStart
* @see #onSaveInstanceState
* @see #onRestoreInstanceState
* @see #onPostCreate
*/
@MainThread
@CallSuper
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
if (mLastNonConfigurationInstances != null) {
mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
}
if (mActivityInfo.parentActivityName != null) {
if (mActionBar == null) {
mEnableDefaultActionBarUp = true;
} else {
mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
}
}
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.fragments : null);
}
mFragments.dispatchCreate();
getApplication().dispatchActivityCreated(this, savedInstanceState);
if (mVoiceInteractor != null) {
mVoiceInteractor.attachActivity(this);
}
mCalled = true;
}
/**
* Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
* the attribute {@link android.R.attr#persistableMode} set to
* <code>persistAcrossReboots</code>.
*
* @param savedInstanceState if the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in {@link #onSaveInstanceState}.
* <b><i>Note: Otherwise it is null.</i></b>
* @param persistentState if the activity is being re-initialized after
* previously being shut down or powered off then this Bundle contains the data it most
* recently supplied to outPersistentState in {@link #onSaveInstanceState}.
* <b><i>Note: Otherwise it is null.</i></b>
*
* @see #onCreate(android.os.Bundle)
* @see #onStart
* @see #onSaveInstanceState
* @see #onRestoreInstanceState
* @see #onPostCreate
*/
public void onCreate(@Nullable Bundle savedInstanceState,
@Nullable PersistableBundle persistentState) {
onCreate(savedInstanceState);
}
/**
* The hook for {@link ActivityThread} to restore the state of this activity.
*
* Calls {@link #onSaveInstanceState(android.os.Bundle)} and
* {@link #restoreManagedDialogs(android.os.Bundle)}.
*
* @param savedInstanceState contains the saved state
*/
final void performRestoreInstanceState(Bundle savedInstanceState) {
onRestoreInstanceState(savedInstanceState);
restoreManagedDialogs(savedInstanceState);
}
/**
* The hook for {@link ActivityThread} to restore the state of this activity.
*
* Calls {@link #onSaveInstanceState(android.os.Bundle)} and
* {@link #restoreManagedDialogs(android.os.Bundle)}.
*
* @param savedInstanceState contains the saved state
* @param persistentState contains the persistable saved state
*/
final void performRestoreInstanceState(Bundle savedInstanceState,
PersistableBundle persistentState) {
onRestoreInstanceState(savedInstanceState, persistentState);
if (savedInstanceState != null) {
restoreManagedDialogs(savedInstanceState);
}
}
/**
* This method is called after {@link #onStart} when the activity is
* being re-initialized from a previously saved state, given here in
* <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
* to restore their state, but it is sometimes convenient to do it here
* after all of the initialization has been done or to allow subclasses to
* decide whether to use your default implementation. The default
* implementation of this method performs a restore of any view state that
* had previously been frozen by {@link #onSaveInstanceState}.
*
* <p>This method is called between {@link #onStart} and
* {@link #onPostCreate}.
*
* @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
*
* @see #onCreate
* @see #onPostCreate
* @see #onResume
* @see #onSaveInstanceState
*/
protected void onRestoreInstanceState(Bundle savedInstanceState) {