preface

  • learnAndroidFor 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 daysActivityThe 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 lookAndroidactivityWhat exactly does it have?
  • Borrow a very popular picture on the Internet to take you to understandActivity

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 createddialogActivityLifecycle methods are not executed
  • But if you jump to something that’s not full screenActivityThen, of course, it is executed according to the normal life cycle
  • namelyonPasue() -> onPause()(The original will not be executedActivityonStop()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 theActivityonCreate() —> onStart() —> onResume()ActivityEnter the running state.
  • Executed when the screen is lockedonPause()onStop(), and should be executed when the screen is ononStart() onResume()

  • ActivityStep back: in the presentActivityGo to the newActivityInterface or byHomeKey back to home screen:onPause() —> onStop(), enter a stasis state.
  • ActivityBack to the foreground:onRestart() —> onStart() —> onResume(), returns to the running state again.
  • ActivityRetreat to background: And the system is out of memory, the system will kill the background stateActivityIf 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 oneActivityJust hit the back key, and we write code to exitactivityDirect callfinish()The method will do.

  • To send a specific broadcast:
  1. When the application needs to end, a specific broadcast is sent, eachActivityWhen you receive the broadcast, turn it off.
  2. To a certainactivityRegister to receive the intention of receiving a broadcastregisterReceiver(receiver, filter)
  3. If the receiver is closedactivityThe radioactivity finish()
  • Recursive exit
  1. Just callfinish()Method to put the currentActivityexit
  2. Opening a new oneActivityThe use ofstartActivityForResult, and then add their own logo, inonActivityResultThe recursion is closed.
  • Actually,
  1. Also throughintentflagTo implement theintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)Activate a new oneactivity.
  2. If this task already exists in the stackActivitySo the system will take thisActivityAll of the aboveActivityTake out.
  3. It’s basically givingActivityThe boot mode is set tosingleTask
  • Record openActivity
  1. Every time you open oneActivity“Write it down.
  2. Close each one when you need to exitActivity

1.6 How does an Activity Perform its life cycle when the Screen is Locked or unlocked

  • Executed when the screen is lockedonPause()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 definitionActivityThe theme of the second is overwrittenActivityoverridePendingTransitionMethods.
  • By setting the theme style instyles.xmlEdit the code, addthemes.xmlFile:AndroidManifest.xmlSpecified inActivityThe specifiedtheme.
  • overwriteoverridePendingTransitionMethods:overridePendingTransition(R.anim.fade, R.anim.hold);

1.8 Four states of an Activity

  • runnig: The user can click,activityAt the top of the stack.
  • pausedactivityOut of focus when by a non – full – screenactivityTo occupy or be filled with a transparentactivityOverwrite, in this stateactivityInstead of destroying it, all of its status information and member variables remain, but cannot be clicked. (Memory tight situation, thisactivityMay be recycled)

  • stopped: thisactivityBy anotheractivityCompletely covered, but thisactivityAll state information and member variables of the
  • killed: thisactivityHas been destroyed, all its status information and member variables no longer exist.

1.9 How do I Handle An Abnormal Exit

  • ActivityException exit –>onPause() –> onSaveInstanceState() –> onStop() –> onDestory()
  • One thing to noteonSaveInstanceState()The methods andonPauseIt’s not strictly sequential. It could beonPauseBefore, it might be called after, but inonStop()Method before calling
  • It is restarted after an abnormal exitActivity –> 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 thisActivityOr just quit the whole thingapp
  • If you want to restore inonSaveInstanceState()To save the data inonRestoreInstanceState()To recover from
  • If you want to quitappCatch the global exception message and exitapp
  • Of course personal advice is to useUncaughtExceotionHandlerTo catch the global exception and exitappOperation, 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

  • ActivityThere are four kindslaunchModestandardsingleTopsingleTasksingleInstance

  • StandardMode (default mode)
  1. Note: Each time an Activity is started, a new instance is created on the stack, regardless of whether the instance exists.

  2. Life cycle: Each time an instance of an Activity is created with a typical life cycle, its onCreate, onStart, and onResume classes are called.

  3. 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.

  • SingleTopPattern (Top of stack reuse pattern)
  1. 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.

  2. 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).

  3. 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.

  • SingleTaskPattern (in-stack reuse pattern)
  1. 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.

  2. 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.

  3. Life cycle: Same as in case 1 of SingleTop pattern. The onNewIntent method in the Activity is simply called back again

  4. 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.

  • SingleInstancePattern (single instance pattern)
  1. 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.

  2. 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.

  3. 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

  • inManifest.xmlSpecified in theActivityBoot mode
  1. A static method of specifying
  2. inManifest.xmlThe document states thatActivitySpecify its startup mode at the same time
  3. This creates jumps in code according to the specified patternActivity
  • Start theActivityAt the right time. inIntentSpecify boot mode to createActivity
  1. A dynamic startup mode
  2. innewaIntent
  3. throughIntentaddFlagsMethod to dynamically specify a boot mode.
  • Note: Both methods can be usedActivitySpecify boot mode, but there is a difference.
  1. 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.

  2. 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:

  • SingleTaskApplication scenarios of patterns
  1. The most common application scenario is to keep our application open with only oneActivityThe instance.
  2. The most typical example is the home page shown in the application (HomePages).
  3. Assume that the user jumps to another page from the home page and wants to return to the home page after several operationsSingleTaskMode, in the process of clicking back to see the home page multiple times, this is clearly not reasonable design.
  • SingleTopApplication scenarios of patterns
  1. Suppose you’re in the currentActivityTo start the same type ofActivity
  2. This type is recommendedActivityThe boot mode of theSingleTopCan reduce Activity creation and save memory!
  • Note: reuseActivityLife cycle callback when
  1. There’s one more thing to consider hereActivityProblems with page parameters when jumping.
  2. Because when aActivitySet upSingleToporSingleTaskAfter mode, jump to thisActivityReuse of originalActivityThis is the caseActivityonCreateThe method will not run again.onCreateMethods are created only the first timeActivityIs run.
  3. The generalonCreateMethod to initialize the data on the page,UIInitialization, 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
  4. If the data displayed on the page is throughgetInten()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 inActivityonCreateMethod to perform too many heavy operations, and inonPasueMethods 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 understandActivityStart 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
  1. Role is toActivityThe specified"SingleTask"Boot mode. With theAndroidMainfest.xmlSpecify the same effect
  • FLAG_ACTIVITY_SINGLE_TOP
  1. Role is toActivityThe specified"SingleTop"Boot mode, followAndroidMainfest.xmlSpecify the same effect.
  • FLAG_ACTIVITY_CLEAN_TOP
  1. Having this flag bitActivity, will start with theActivityOther tasks on the same stackActivityOut of the stack.
  2. General andSingleTaskBoot modes appear together.
  3. It will be finishedSingleTaskThe role of.
  4. But in factSingleTaskStartup mode has the effect of this flag bit by default
  • FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
  1. Having this flag bitActivityNot in historyActivityThe list of
  2. Usage scenarios: In some cases we don’t want the user to go back through the history listActivity“, the tag bit reflects its effect.
  3. It is equivalent toxmlSpecified in theActivityProperties.

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

  • IntentThere 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 to1MBWithin (1024KB
  • We use transferBitmapThe 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 tellIntentThe transmission capacity is in1MBWithin.

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 pressHOMEAfter how many other programs to run, naturally do not knowactivity AWhether it will be destroyed
  • So the system callsonSaveInstanceState(), which gives users the opportunity to save some non-permanent data. The analysis of the following cases follows this principle:
  1. When the user pressesHOMEkey
  2. Long pressHOMEKey to run another program
  3. When the lock screen
  4. fromactivity AStart a new one inactivity
  5. 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

  • useadb shell amThe command
  1. amStart aactivity
  2. adb shell am start com.example.fuchenxuan/.MainActivity
  3. amTo send a broadcast, useaction
  4. 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 aScheme

  • To obtainSchemeJump parameters

  • Call way
  1. Native calls

  1. HTML call

  1. 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:ActivityApplicationAre allContextThe subclass.
  • ContextLiterally, 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.ContextThe maintenance is currentActivityThe life cycle of,ApplicationIt maintains the life cycle of the entire project.
  • usecontextBe 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:

  1. What is a ActivityRecord
  2. What is a TaskRecord
  3. What is a ActivityManagerService

4.5 What is An Activity

  • One of four components, usually one for each user interfaceactivity
  • activityContextSubclass, while implementingwindow.callbackkeyevent.callbackCan handle events that interact with form users.
  • Commonly used in development areFragmentActivityListActivityTabActivity(The Android 4.0FragmentReplace)

Five, the process


5.1 Android Process Priority

  • Foreground/visible/service/background/empty

5.1.1 Foreground Process: Foreground Process

  • The user is interacting withActivity(onResume()
  • When aServiceThe binding is interactingActivity
  • Be actively called to the foregroundService(startForeground()
  • The component is performing a lifecycle callback (onCreate()onStart()onDestory()
  • BroadcastReceiverBeing performedonReceive()

5.1.2 Visible Processes: Visible Processes

  • ourActivityinonPause()(No entryonStop()
  • Bind to the foregroundActivityService

5.1.3 Service Process: Service process

  • simplestartService()Start.

5.1.4 Background Processes: Background processes

  • Processes that have no direct impact on usersActivityIn aonStop()From time to time.
  • android:process=":xxx"

5.1.5 Empty Process: Empty Process

  • Components that do not contain any activity. (AndroidDesigned 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:
  1. Hosts an activity that is not the foreground, but is still visible to the user (itsonPause()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.
  2. 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 userActivityThe object’sonStop()Method (if anyUIOther 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 oneLRU(least recently usedThe least recently used, and familiar if you’ve studied operating systems, is the page replacement algorithm for memoryLRUList 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

  • ANRCalled the,Application Not Responding
  • inAndroidIf 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 displayANRTo the user.

5.6.3 ANR Timeout duration varies according to Android Components

  • Different components occurANRThe main thread (ActivityService) is5Second,BroadCastReceiver10Seconds.

5.6.4 Solution

  1. Take all the time-consuming operations, like accessing the network,SocketCommunication, query a lotSQLStatements, complex logic calculations, and so on are put into child threads and passed throughhandler.sendMessagerunonUITreadAsyncTaskEtc.UITo ensure smooth operation of the user interface.
  2. 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

  • aTaskIt containsactivityThe collection,androidThe system can be managed by task stack in orderactivity
  • There may be more than one task stack in an app, and in some cases, oneactivityYou can also have a task stack to yourself (singleInstanceMode-enabledactivity

conclusion


  1. This article basically covers itAndroid ActivityAll knowledge points. forAppTo start,AMSI hope you can follow the link in the article orGoogleThe form of search continues to unfold.
  2. Focus on: aboutAndroidI’ve just finished summarizing activities so far, and I’ll move on to theServiceBroadcastRecevier, 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!