preface
- learn
Android
For some time, I have been focusing on learning new things. Recently, I found that I forgot a lot of things I usually use. I plan to learn about them in these two daysActivity
The content of the problem in the form of carding out, but also for everyone to check gaps.
In this article, I will change the habit of writing blog in the past, using XMind to present all knowledge points in the form of mind mapping, welcome to eat ~ ~
The article directories
For your convenience, I will set up a warehouse on GitHub
-
The warehouse content is updated synchronously with the blog. Due to my rare earth mining brief book CSDN blog park and other sites, there are new content published. So you can directly follow the warehouse, so as not to miss the highlights!
-
Warehouse address: Super dry goods! Carefully summarized Android, JVM, algorithm, etc., you handsome old iron support! For a Star!
God figure
- Before we begin, let’s have a look
Android
的activity
What exactly does it have? - Borrow a very popular picture on the Internet to take you to understand
Activity
First, life cycle
- Let’s start with the famous picture
- Let’s take a look at the specific methods of callbacks in the lifecycle, one by one:
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
-
When android:configChanges is not set for the Activity, the various life cycles are re-called for screen cuts, once for landscape and twice for portrait
-
When you set the Activity’s Android :configChanges=” Orientation “, the various life cycles will still be called again, and only once for landscape and portrait
-
Set up the Activity of the android: configChanges = “orientation” | “keyboardHidden, cut the screen each life cycle will not call again, will only implement onConfigurationChanged method
-
Note: One more, and very important, detail of an Android change! When API >12, you need to add the screenSize attribute, otherwise the system will rebuild the Activity even if you set orientation when the screen switches!
-
Horizontal and vertical switching life cycle execution
1.3 Change process of Activity life cycle in different scenarios
- Start the
Activity
:onCreate()
—>onStart()
—>onResume()
,Activity
Enter the running state. - Executed when the screen is locked
onPause()
和onStop()
, and should be executed when the screen is ononStart()
onResume()
Activity
Step back: in the presentActivity
Go to the newActivity
Interface or byHome
Key back to home screen:onPause()
—>onStop()
, enter a stasis state.Activity
Back to the foreground:onRestart()
—>onStart()
—>onResume()
, returns to the running state again.Activity
Retreat to background: And the system is out of memory, the system will kill the background stateActivity
If I go back to thisActivity
, it will goonCreate()
–>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 Exit Application where multiple Activities have been invoked
- Usually the user exits one
Activity
Just hit the back key, and we write code to exitactivity
Direct callfinish()
The method will do.
- To send a specific broadcast:
- When the application needs to end, a specific broadcast is sent, each
Activity
When you receive the broadcast, turn it off. - To a certain
activity
Register to receive the intention of receiving a broadcastregisterReceiver(receiver, filter)
- If the receiver is closed
activity
The radioactivity finish()
掉
- Recursive exit
- Just call
finish()
Method to put the currentActivity
exit - Opening a new one
Activity
The use ofstartActivityForResult
, and then add their own logo, inonActivityResult
The recursion is closed.
- Actually,
- Also through
intent
的flag
To implement theintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
Activate a new oneactivity
. - If this task already exists in the stack
Activity
So the system will take thisActivity
All of the aboveActivity
Take out. - It’s basically giving
Activity
The boot mode is set tosingleTask
。
- Record open
Activity
- Every time you open one
Activity
“Write it down. - Close each one when you need to exit
Activity
1.6 How does an Activity Perform its life cycle when the Screen is Locked or unlocked
- Executed when the screen is locked
onPause()
和onStop()
, and should be executed when the screen is ononStart()
onResume()
1.7 Modify the Activity entry and exit animations
- 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.8 Four states of an Activity
runnig
: The user can click,activity
At the top of the stack.paused
:activity
Out of focus when by a non – full – screenactivity
To occupy or be filled with a transparentactivity
Overwrite, in this stateactivity
Instead of destroying it, all of its status information and member variables remain, but cannot be clicked. (Memory tight situation, thisactivity
May be recycled)
stopped
: thisactivity
By anotheractivity
Completely covered, but thisactivity
All state information and member variables of thekilled
: thisactivity
Has been destroyed, all its status information and member variables no longer exist.
1.9 How do I Handle An Abnormal Exit
Activity
Exception exit –>onPause()
–>onSaveInstanceState()
–>onStop()
–>onDestory()
- One thing to note
onSaveInstanceState()
The methods andonPause
It’s not strictly sequential. It could beonPause
Before, it might be called after, but inonStop()
Method before calling - It is restarted after an abnormal exit
Activity
–>onCreate()
–>onStart()
–>onRestoreInstanceState()
–>onResume()
- Once you understand the execution of the lifecycle, you can answer, first of all, what the interviewer means: restart and resume this
Activity
Or just quit the whole thingapp
- If you want to restore in
onSaveInstanceState()
To save the data inonRestoreInstanceState()
To recover from - If you want to quit
app
Catch the global exception message and exitapp
- Of course personal advice is to use
UncaughtExceotionHandler
To catch the global exception and exitapp
Operation, this will reduce the sequela caused by the previous crash!
1.10 What is onNewIntent
-
If an IntentActivity is at the top of the task stack, that is, an Activity that was previously started is now in the onPause or onStop state, then another application sends an Intent
-
The execution sequence is onNewIntent, onRestart, onStart, and onResume.
Second, the startup mode
2.1 Startup Mode
Activity
There are four kindslaunchMode
:standard
、singleTop
、singleTask
、singleInstance
。
Standard
Mode (default mode)
-
Note: Each time an Activity is started, a new instance is created on the stack, regardless of whether the instance exists.
-
Life cycle: Each time an instance of an Activity is created with a typical life cycle, its onCreate, onStart, and onResume classes are called.
-
For example, there are three activities in the Activity stack: A, B, and C. C is at the top of the stack and starts in Standard mode. If you add a click event to a C Activity, you need to jump to another C Activity of the same type. As a result, another C Activity enters the stack and becomes the top of the stack.
SingleTop
Pattern (Top of stack reuse pattern)
-
Note: There are two processing cases: when the Activity to be created is already at the top of the stack, it will reuse the Activity at the top of the stack directly. No new activities are created; If the Activity to be created is not at the top of the stack, a new Activity will be created again, as in Standard mode.
-
Life cycle: If the Activity at the top of the stack is reused directly in case 1, its onCreate and onStart will not be called by the system because it has not changed. However, a new method, onNewIntent, is called back (this method is not called back when the Activity is normally created).
-
For example, there are three activities (A, B, and C) in the Activity stack, and C is at the top of the stack and starts in SingleTop mode. If you add a click event to a C Activity, you need to jump to another C Activity of the same type. The result is to reuse the C Activity at the top of the stack directly. Case 2: If you add A click event to C Activity, you need to jump to another A Activity. The result is to create a new Activity onto the stack. Become the top of the stack.
SingleTask
Pattern (in-stack reuse pattern)
-
Note: If the Activity you want to create is already on the stack, you will not create a new Activity, but destroy all other activities on top of the existing Activity in the stack, making it the top of the stack.
-
If it is started in another application, a new task will be created and the Activity will be started in that task. SingleTask allows other activities to coexist with it in a task, that is, If I open a new Activity in the singleTask instance, the new Activity will still be in the singleTask instance task.
-
Life cycle: Same as in case 1 of SingleTop pattern. The onNewIntent method in the Activity is simply called back again
-
For example, there are three activities in the Activity stack: A, B, and C. At this time, C is at the top of the stack and the startup mode is SingleTask mode. If you add a click event to a C Activity, you need to jump to another C Activity of the same type. The result is to use the C Activity directly at the top of the stack. Case 2: If you add A click event to C Activity, you need to jump to another A Activity. The result is that all B and C on an Activity are destroyed, making A Activity the top of the stack.
SingleInstance
Pattern (single instance pattern)
-
Note: SingleInstance is a special global singleton mode, which is an enhanced SingleTask mode. In addition to all of its features, it has the added bonus of having only one instance, and that instance runs independently in a task that has only that instance and does not allow other activities to exist.
-
This application is often used in the system, 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.
-
For example, if A Activity is in this mode, start A. The system creates a separate task stack for it due to the nature of in-stack reuse. Any possible request will not create a new Activity 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.
-
Scoping: The first method does not directly specify the FLAG_ACTIVITY_CLEAR_TOP flag for an Activity, and the other method does not specify the singleInstance mode for an Activity.
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:
-
The startup mode of the CourseDetailActivity in the above code is set to SingleTop in the configuration file. According to the introduction of the startup mode above, when the CourseDetailActivity is at the top of the stack.
-
Rejumping the page to the CourseDetailActivity will reuse the original Activity directly, and the data the page needs to display is derived from the getIntent() method, but the initData() method will not be called again, so the page cannot display new data.
-
The onNewIntent (Intent Intent) callback is an Intent Intent. This method passes in the latest intent so that we can solve the above problem. The suggested approach here is to go to setIntent again. Then we initialize the data and UI again. 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 Startup Process
-
Attention! This is not to answer the Activity lifecycle!
-
Three minutes to understand
Activity
Start the process
2.6 the Activity of Flags
-
FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_SINGLE_TOP, etc. It can also affect the state of an Activity, such as FLAG_ACTIVITY_CLEAN_TOP and FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS.
-
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.7 onNewInstent() When 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() and onRestoreInstanceState() are not lifecycle methods and, unlike lifecycle methods such as onCreate() and onPause(), they do not necessarily trigger.
-
OnSaveInstanceState () method, which is called when an Activity is destroyed by the system due to an unexpected situation (e.g., running out of memory or the user pressing the Home button).
-
But onSaveInstanceState() is not called when the user actively destroys an Activity, for example by pressing the return key in the application.
-
Unless the activity is not actively destroyed by the user, onSaveInstanceState() is usually only good for temporary states, while onPause() is good for persistent 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
3.6 Scheme Forward Protocol
3.6.1 definition
-
The server can customize the jump app page
-
App can jump to another APP page through Scheme
-
You can jump to the native page of app through H5 page
3.6.2 Protocol Format:
-
Qh Indicates the Scheme protocol name
-
Test indicates the address domain used by Scheme
-
8080 indicates the port number of the changed path
-
/ Goods represents the specified page (path)
-
GoodsId and name represent the two parameters passed
3.6.3 Scheme using
- To define a
Scheme
- To obtain
Scheme
Jump parameters
- Call way
- Native calls
- HTML call
- Checks whether a Scheme is valid
- For more information about the Scheme jump protocol, see the following blog, standing on the shoulders of giants, to see further
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 abstract class, and Android provides a ContextIml for this abstract class.
-
It allows you to retrieve application resources and classes, as well as application-level operations such as starting an Activity, sending a broadcast, receiving intEnts, messages, and so on.
4.2.1 Attach a Context inheritance diagram
4.3 Getting the Activity object on the current screen
-
Using ActivityLifecycleCallbacks
-
How does Android get the current Activity instance object?
4.4 Activity Management Mechanism
-
The management mechanism for an Activity
-
The interviewer asks this question to see how well you know Activity:
- What is a ActivityRecord
- What is a TaskRecord
- What is a ActivityManagerService
4.5 What is An Activity
- One of four components, usually one for each user interface
activity
。 activity
是Context
Subclass, while implementingwindow.callback
和keyevent.callback
Can handle events that interact with form users.- Commonly used in development are
FragmentActivity
、ListActivity
、TabActivity
(The Android 4.0
被Fragment
Replace)
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()
) - The component is performing a lifecycle callback (
onCreate()
、onStart()
、onDestory()
) 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
-
A service process is a process started by the startService() method, but is not a foreground and 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 to serve as a cache to speed up the next startup of the component. The system process kills these processes to balance the entire system resources between the process cache and the potential kernel cache.
-
Android processes are reclaimed from first to last in the following order: 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
)
conclusion
- This article basically covers it
Android Activity
All knowledge points. forApp
To start,AMS
I hope you can follow the link in the article orGoogle
The form of search continues to unfold. Focus on
: aboutAndroid
I’ve just finished summarizing activities so far, and I’ll move on to theService
,BroadcastRecevier
, and event distribution, sliding conflict, new energy optimization and other important modules, a comprehensive summary, welcome your attentionThe nuggets of _yuanhaoTo receive updates in a timely manner
Code word is not easy, your praise is my summary of the biggest power!
-
Due to my “rare earth nuggets”, “Jian Shu”, “CSDN”, “Blog park” and other sites, there are new content released. So you can directly follow my GitHub repository, so as not to miss the great content!
-
Warehouse address: Super dry goods! Carefully summarized Android, JVM, algorithm, etc., you handsome old iron support! For a Star!
-
More than 10,000 words long article, plus exquisite mind map, remember to like oh, welcome to pay attention to the excavation of _Yuanhao, we will see you in the next article!