This article will answer some of your questions:
-
What are the different withdrawals in the Activity lifecycle for different scenarios?
-
What are the startup modes of the Activity? What’s the difference?
-
How does an Activity process data?
-
What’s the relationship between an Activity and a Context?
-
What processes are available in Android?
First, life cycle
1.1 Dialog when pop-up
- If it’s purely created
dialog
,Activity
Lifecycle methods are not executed - But if you jump to something that’s not full screen
Activity
Then, of course, it is executed according to the normal life cycle - namely
onPasue()
->onPause()
(The original will not be executedActivity
的onStop()
Otherwise, the previous page will not show)
1.2 When switching between horizontal and vertical screens
- Don’t set
Activity
的android:configChanges
When the screen is cut, each life cycle will be called again, once for landscape and twice for portrait (before Android3.2). - Set up the
Activity
的android:configChanges="orientation"
, each life cycle will be called again when cutting the screen. Cutting the horizontal screen and portrait screen will be executed only once - Set up the
Activity
的android:configChanges="orientation|keyboardHidden"
, the screen cut does not re-call the various life cycles, only executesonConfigurationChanged
methods - Note: One more thing, very important, one
Android
Change details! whenAPI >12
“, you need to joinscreenSize
Property, otherwise the screen switches when you set itorientation
The system will be rebuiltActivity
!
1.3 Change process of Activity life cycle in different scenarios
-
Start the Activity: onCreate() –> onStart() –> onResume(), and the Activity starts.
-
OnPause () and onStop() are executed when the screen is locked, onStart() onResume() is executed when the screen is opened, and onStart() onResume() is executed when the screen is opened.
-
An Activity exits the background: The current Activity moves to a new Activity screen or returns to the Home screen by pressing the Home button: onPause() –> onStop().
-
The Activity returns to the foreground: onRestart() –> onStart() –> onResume(), and returns to the running state again.
-
If the system is running out of memory, the system will kill the Activity in the background state. If it returns to the Activity again, onCreate() –> onStart() –> onResume()
1.4 Setting an Activity to look like a window
Simply configure the following properties for our Activity. android:theme=”@android:style/Theme.Dialog”
1.5 Modify the Activity to enter and exit animation
- You can do it in two ways. One is by definition
Activity
The theme of the second is overwrittenActivity
的overridePendingTransition
Methods. - By setting the theme style in
styles.xml
Edit the code, addthemes.xml
File:AndroidManifest.xml
Specified inActivity
The specifiedtheme
. - overwrite
overridePendingTransition
Methods:overridePendingTransition(R.anim.fade, R.anim.hold)
;
1.6 Four states of the Activity
-
Runnig: The user can click and the activity is at the top of the stack.
-
Paused: When an activity loses focus and is occupied by a non-full-screen activity or covered by a transparent activity, the state of the activity has not been destroyed, and all its state information and member variables remain, but cannot be clicked. (The activity may be reclaimed if memory is tight.)
-
Stopped: This activity is completely overwritten by another activity, but all of its state information and member variables remain (except for memory constraints)
-
Killed: The activity was destroyed, and all its state information and member variables no longer exist.
1.7 How to Handle An Abnormal Exit
-
When the Activity stops abnormally –> onPause() –> onSaveInstanceState() –> onStop() –> onDestory()
-
Note that onSaveInstanceState() is not called in strict sequence with onPause. It may be called before or after onPause, but before onStop()
-
Restart the Activity after an abnormal exit –> onCreate() –> onStart() –> onRestoreInstanceState() –> onResume()
-
Once you understand the execution of this lifecycle, you’ll be able to answer this question. First, you need to know what the interviewer means: restart the Activity and resume it, or simply exit the app
-
If you want to restore, save the data in onSaveInstanceState() and restore it in onRestoreInstanceState()
-
If you want to exit the app, you need to catch the global exception message and exit the app
-
UncaughtExceotionHandler is recommended to use UncaughtExceotionHandler to catch global exceptions and exit app. This will reduce the sequelas caused by previous crashes.
1.8 What is onNewIntent
- if
IntentActivity
It’s at the top of the task stack, which means it was opened beforeActivity
At presentonPause
、onStop
If so, other applications will send itIntent
if - The execution sequence is:
onNewIntent
.onRestart
.onStart
.onResume
.
Second, the startup mode
2.1 Startup Mode
-
There are four launchmodes for activities: Standard, singleTop, singleTask, and singleInstance.
-
Standard mode (default mode)
- Instructions: Start one at a time
Activity
A new instance is created on the stack again, regardless of whether the instance exists. - Life cycle: Each instance that is created
Activity
The life cycle fits the typical case of itsonCreate
、onStart
、onResume
Will be called. - For example:
Activity
The stack has thisA
、B
、C
,D
fourActivity
, D is at the top of the stack, and the startup mode isStandard
Mode. If theD Activity
To add click event, you need to jump to typeB Activity
. Turns out there’s another oneB Activity
Go to the top of the stack.
SingleTop
Pattern (Top of stack reuse pattern)
- Note: there are two processing cases: need to create
Activity
If it is already at the top of the stack, it will reuse the top of the stack directlyActivity
. No new ones will be createdActivity
; If need to createActivity
Not at the top of the stack, a new one is created againActivity
Into the stack, withStandard
The pattern is the same. - Life cycle: if case 1 is at the top of the stack
Activity
When it is directly reused, itsonCreate
、onStart
Will not be called by the system because it has not changed. But a new approachonNewIntent
Will be called back (Activity
This method is not called back when it is normally created.
- For example:
Activity
The stack has thisA
、B
、C
,D
fourActivity
At this time,D
Is at the top of the stack and the boot mode isSingleTop
Mode. Situation one: YesD Activity
To add a click event, you need to jump to another of the same typeD Activity
. The result is direct reuse of the top of the stackD Activity
.
If you add a click event to C Activity, you need to jump to D Activity. The result is to create a new Activity onto the stack. Become the top of the stack.
SingleTask
Pattern (in-stack reuse pattern)
- Description: If need to create
Activity
When already in the stack, no new ones are created at this pointActivity
Instead, it will exist on the stackActivity
The rest of the aboveActivity
All destroyed, making it the top of the stack. - If you start it in another application, a new one will be created
task
And start this in the taskActivity
,singleTask
Allow otherActivity
Rather than being in atask
In other words, if I’m in thissingleTask
And then open a new oneActivity
This new oneActivity
Will still be insingleTask
An instance oftask
In the. - Life cycle: same
SingleTop
Pattern one is the same. Just another pullbackActivity
In theonNewIntent
methods
- For example:
Activity
The stack has thisA
、B
twoActivity
. At this timeB
Is at the top of the stack and the boot mode isSingleTask
Mode. inB Activity
To add a click event, you need to jump toC Activity
. The result is to create a new oneC Activity
Put it on top of the stack.
Situation two: YesC Activity
To add a click event, need to jump to anotherC Activity
. The result isC Activity
The aboveD
Destruction,C Activity
Become the top of the stack.
SingleInstance
Pattern (single instance pattern)
- Description:
SingleInstance
In particular, it is the global singleton pattern, which is an enhancedSingleTask
Mode. In addition to having all of its features, it is enhanced by the fact that there is only one instance, and that instance runs independently of onetask
In thetask
There is only one instance, and nothing else is allowedActivity
There is. - This is often used in system applications such as
Launch
, lock screen key application and so on, there is only one in the whole system! So we don’t usually use it in our applications. Just know. - Example: For example
A Activity
Yes mode, startA
After. The system creates a separate task stack for it due to the nature of in-stack reuse. Possible requests will not create new onesActivity
Unless the unique task stack is destroyed by the system.
2.2 Use mode of startup Mode
- in
Manifest.xml
Specified in theActivity
Boot mode
- A static method of specifying
- in
Manifest.xml
The document states thatActivity
Specify its startup mode at the same time - This creates jumps in code according to the specified pattern
Activity
。
- Start the
Activity
At the right time. inIntent
Specify boot mode to createActivity
- A dynamic startup mode
- in
new
aIntent
后 - through
Intent
的addFlags
Method to dynamically specify a boot mode.
- Note: Both methods can be used
Activity
Specify boot mode, but there is a difference.
- Priority: Indicates that the other method has a higher priority than the first method. If both methods exist at the same time, the other method shall prevail.
- Limited scope: the first way cannot be
Activity
Specified directlyFLAG_ACTIVITY_CLEAR_TOP
Identification, the other way does not workActivity
The specifiedsingleInstance
Mode.
2.3 Actual Application Scenarios of startup Mode
The Standard mode is the most common of the four modes, with no special attention. The SingleInstance mode is the singleton mode of the whole system, which is generally not applied in our application. Therefore, the application scenarios of SingleTop and SingleTask modes are explained in detail here:
SingleTask
Application scenarios of patterns
- The most common application scenario is to keep our application open with only one
Activity
The instance. - The most typical example is the home page shown in the application (
Home
Pages). - Assume that the user jumps to another page from the home page and wants to return to the home page after several operations
SingleTask
Mode, in the process of clicking back to see the home page multiple times, this is clearly not reasonable design.
SingleTop
Application scenarios of patterns
- Suppose you’re in the current
Activity
To start the same type ofActivity
- This type is recommended
Activity
The boot mode of theSingleTop
Can reduce Activity creation and save memory!
- Note: reuse
Activity
Life cycle callback when
- There’s one more thing to consider here
Activity
Problems with page parameters when jumping. - Because when a
Activity
Set upSingleTop
orSingleTask
After mode, jump to thisActivity
Reuse of originalActivity
This is the caseActivity
的onCreate
The method will not run again.onCreate
Methods are created only the first timeActivity
Is run. - The general
onCreate
Method to initialize the data on the page,UI
Initialization, assuming that the display data of the page is irrelevant to the parameters passed by the page jump, you do not need to worry about this problem - If the data displayed on the page is through
getInten()
Method, then the problem arises:getInten()
Get old data all the time, cannot receive new data when jump!
- Here is an example to explain:
- In the code above
CourseDetailActivity
The startup mode is set in the configuration fileSingleTop
Mode, according to the introduction of the above startup mode, whenCourseDetailActivity
At the top of the stack. - Jump to the page again
CourseDetailActivity
Will just reuse the originalActivity
And the data that this page needs to display is fromgetIntent()
The way, butinitData()
Method is not called again, and the page cannot display new data. - Of course, the system has already thought of this situation for us, and we need another callback
OnNewIntent (Intent Intent)
Methods. This method passes in the latestintent
In this way, we can solve the above problems. The suggested approach here is to go againsetIntent
. And then we initialize the sum againUI
. The code looks like this:
- This allows you to jump back and forth on a page and display different content.
2.4 Quickly start an Activity
- This problem is also relatively simple, is not in
Activity
的onCreate
Method to perform too many heavy operations, and inonPasue
Methods also do not do too many time-consuming operations.
2.5 the Activity of Flags
- The flag bit can both set the Activity’s launch mode, as described above, and specify the launch mode dynamically, for example
FLAG_ACTIVITY_NEW_TASK
和FLAG_ACTIVITY_SINGLE_TOP
And so on. It can also affectActivity
The operating state of, for exampleFLAG_ACTIVITY_CLEAN_TOP
和FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
And so on. - Here are a few basic flag bits, do not memorize, understand a few can, if necessary to check the official documentation.
FLAG_ACTIVITY_NEW_TASK
- Role is to
Activity
The specified"SingleTask"
Boot mode. With theAndroidMainfest.xml
Specify the same effect
FLAG_ACTIVITY_SINGLE_TOP
- Role is to
Activity
The specified"SingleTop"
Boot mode, followAndroidMainfest.xml
Specify the same effect.
FLAG_ACTIVITY_CLEAN_TOP
- Having this flag bit
Activity
, will start with theActivity
Other tasks on the same stackActivity
Out of the stack. - General and
SingleTask
Boot modes appear together. - It will be finished
SingleTask
The role of. - But in fact
SingleTask
Startup mode has the effect of this flag bit by default
FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
- Having this flag bit
Activity
Not in historyActivity
The list of - Usage scenarios: In some cases we don’t want the user to go back through the history list
Activity
“, the tag bit reflects its effect. - It is equivalent to
xml
Specified in theActivity
Properties.
2.6 When the onNewInstent() method is executed
When an instance of the Activity already exists and is SingleTask or SingleInstance, Also, onNewInstent() is triggered when the instance is at the top of the stack and starts in SingleTop mode.
Third, the data
3.1 Limit on the size of data transferred between activities through IntEnts
Intent
There is a limit to the size of the data that can be transferred, which is not officially specified here, but it can be determined by experimental methods that the data should be limited to1MB
Within (1024KB
)- We use transfer
Bitmap
The method is found when the image size exceeds1024
(To be precise1020
), the program will flash back, stop running and other abnormalities (different phones have different reactions) - So you can tell
Intent
The transmission capacity is in1MB
Within.
3.2 When the memory is insufficient, the system will kill the activities in the background. If you need to save some temporary states, which method should you use
Activity
的onSaveInstanceState()
和onRestoreInstanceState()
Not lifecycle methods, they’re different fromonCreate()
、onPause()
Life cycle methods, they don’t have to be triggered.onSaveInstanceState()
Method, when the application encounters unexpected situations (such as: insufficient memory, the user directly pressHome
Key) is destroyed by the systemActivity
,onSaveInstanceState()
Will be called.- But when the user takes the initiative to destroy one
Activity
For example, press the back key in the application,onSaveInstanceState()
It won’t get called. - Unless the
activity
Not voluntarily destroyed by the user, usuallyonSaveInstanceState()
Only suitable for preserving some temporary state, whileonPause()
Suitable for persistent storage of data.
3.3 Scenario in which onSaveInstanceState() is executed
- The system doesn’t know when you press
HOME
After how many other programs to run, naturally do not knowactivity A
Whether it will be destroyed - So the system calls
onSaveInstanceState()
, which gives users the opportunity to save some non-permanent data. The analysis of the following cases follows this principle:
- When the user presses
HOME
key - Long press
HOME
Key to run another program - When the lock screen
- from
activity A
Start a new one inactivity
时 - When the screen is switched
3.4 Methods that must be executed when two Activities jump between
Typically, there are two activities called A and B. When activating component B in A, A calls onPause(), and B calls onCreate(), onStart(), and onResume().
B overwrites the form and A calls onStop(). If B were transparent, or dialog style, A’s onStop() method would not be called.
3.5 Using Intent to start a method other than an Activity
- use
adb shell am
The command
am
Start aactivity
adb shell am start com.example.fuchenxuan/.MainActivity
am
To send a broadcast, useaction
adb shell am broadcast -a magcomm.action.TOUCH_LETTER
Fourth, the Context
4.1 Differences between Context, Activity, and Appliction
- The same:
Activity
和Application
Are allContext
The subclass. Context
Literally, it is the meaning of context. In practical application, it does play a role in managing various parameters and variables in the context, so that we can easily access various resources.- Different: The maintenance life cycle is different.
Context
The maintenance is currentActivity
The life cycle of,Application
It maintains the life cycle of the entire project. - use
context
Be careful of memory leaks
4.2 What is Context
- It describes information about an application environment, the context.
- This class is an abstraction (
abstract class
) class,Android
A concrete implementation class that provides the abstract class (ContextIml
). - It allows you to retrieve application resources and classes, as well as application-level operations such as starting an application
Activity
Send broadcast receiveIntent
, information, etc.
Five, the process
5.1 Android Process Priority
- Foreground/visible/service/background/empty
5.1.1 Foreground Process: Foreground Process
- The user is interacting with
Activity
(onResume()
) - When a
Service
The binding is interactingActivity
- Be actively called to the foreground
Service
(startForeground()
) BroadcastReceiver
Being performedonReceive()
5.1.2 Visible Processes: Visible Processes
- our
Activity
inonPause()
(No entryonStop()
) - Bind to the foreground
Activity
的Service
5.1.3 Service Process: Service process
- simple
startService()
Start.
5.1.4 Background Processes: Background processes
- Processes that have no direct impact on users
Activity
In aonStop()
From time to time. android:process=":xxx"
5.1.5 Empty Process: Empty Process
- Components that do not contain any activity. (
Android
Designed for caching purposes, a tradeoff to be taken for faster second startup)
5.2 Visible Processes
Visible process refers to a process in which part of the program interface is visible to the user but does not interact with the user in the foreground. For example, if we pop up a dialog box on an interface (the dialog box is a new Activity) and the original interface behind the dialog box is visible but does not interact with the user, the original interface is a visible process.
- A process is considered visible if it meets any of the following criteria:
- Hosts an activity that is not the foreground, but is still visible to the user (its
onPause()
Method already called). This could happen, for example, if a foreground activity remains visible after a dialog (of another process) runs, such as an input method pop-up. - Hosts a service that is bound to a visual activity.
- A visual process is considered extremely important and cannot be killed except to keep the foreground process running.
5.3 Service Process
- The service process is through
startService()
Method, but is not a foreground or visible process. For example, playing music in the background or downloading music in the background is a service process. - The system keeps them running unless there is not enough memory to keep all foreground and visual processes running.
5.4 Background Processes
- A background process is an activity that holds a current call that is not visible to the user
Activity
The object’sonStop()
Method (if anyUI
Other threads running outside the thread are not affected.
For example, WHEN I am using QQ to chat with others, QQ is the foreground process, but when I click the Home button to make the QQ interface disappear, it will become the background process.
- These processes have no direct impact on the user experience and can be killed at any time to reclaim memory for a foreground, visual, server process.
- There are usually many background processes running, so they stay in one
LRU
(least recently used
The least recently used, and familiar if you’ve studied operating systems, is the page replacement algorithm for memoryLRU
List to ensure that the process with the most recently used activity is killed last.
5.5 empty process
- An empty process is one that has no active application components and contains no active components.
- The only reason to keep this process available is as a
cache
To increase the speed of the next startup of the component. The system process kills these processes in order to processcache
And the underlying kernelcache
Balance the entire system resources between. android
The process recycling sequence is: empty process, background process, service process, visible process, foreground process.
5.6 What is ANR and how can it be avoided
5.6.1 What is ANR
ANR
Called the,Application Not Responding
。- in
Android
If your application has not responded for a period of time, the system will present the user with a dialog box called the Application Non-response dialog box.
5.6.2 User Behavior
- The user can choose to keep the program running or stop it.
- They don’t want to have to deal with this dialog every time they use your application.
- Therefore, it is important to design responsiveness in the program so that the system does not display
ANR
To the user.
5.6.3 ANR Timeout duration varies according to Android Components
- Different components occur
ANR
The main thread (Activity
、Service
) is5
Second,BroadCastReceiver
是10
Seconds.
5.6.4 Solution
- Take all the time-consuming operations, like accessing the network,
Socket
Communication, query a lotSQL
Statements, complex logic calculations, and so on are put into child threads and passed throughhandler.sendMessage
、runonUITread
、AsyncTask
Etc.UI
To ensure smooth operation of the user interface. - If a time-consuming operation requires the user to wait, a progress bar can be displayed on the interface.
5.7 Android Task Stack Task
- a
Task
It containsactivity
The collection,android
The system can be managed by task stack in orderactivity
- There may be more than one task stack in an app, and in some cases, one
activity
You can also have a task stack to yourself (singleInstance
Mode-enabledactivity
)