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

  • Don’t setActivityandroid:configChangesWhen the screen is cut, each life cycle will be called again, once for landscape and twice for portrait (before Android3.2).
  • Set up theActivityandroid: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 theActivityandroid:configChanges="orientation|keyboardHidden", the screen cut does not re-call the various life cycles, only executesonConfigurationChangedmethods
  • Note: One more thing, very important, oneAndroidChange details! whenAPI >12“, you need to joinscreenSizeProperty, otherwise the screen switches when you set itorientationThe 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 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.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

  • ifIntentActivityIt’s at the top of the task stack, which means it was opened beforeActivityAt presentonPauseonStopIf so, other applications will send itIntentif
  • 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)

  1. Instructions: Start one at a timeActivityA new instance is created on the stack again, regardless of whether the instance exists.
  2. Life cycle: Each instance that is createdActivityThe life cycle fits the typical case of itsonCreateonStartonResumeWill be called.
  3. For example:ActivityThe stack has thisABC,DfourActivity, D is at the top of the stack, and the startup mode isStandardMode. If theD ActivityTo add click event, you need to jump to typeB Activity. Turns out there’s another oneB ActivityGo to the top of the stack.

  • SingleTopPattern (Top of stack reuse pattern)
  1. Note: there are two processing cases: need to createActivityIf 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 createActivityNot at the top of the stack, a new one is created againActivityInto the stack, withStandardThe pattern is the same.
  2. Life cycle: if case 1 is at the top of the stackActivityWhen it is directly reused, itsonCreateonStartWill not be called by the system because it has not changed. But a new approachonNewIntentWill be called back (ActivityThis method is not called back when it is normally created.

  1. For example:ActivityThe stack has thisABC,DfourActivityAt this time,DIs at the top of the stack and the boot mode isSingleTopMode. Situation one: YesD ActivityTo 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.

  • SingleTaskPattern (in-stack reuse pattern)
  1. Description: If need to createActivityWhen already in the stack, no new ones are created at this pointActivityInstead, it will exist on the stackActivityThe rest of the aboveActivityAll destroyed, making it the top of the stack.
  2. If you start it in another application, a new one will be createdtaskAnd start this in the taskActivitysingleTaskAllow otherActivityRather than being in ataskIn other words, if I’m in thissingleTaskAnd then open a new oneActivityThis new oneActivityWill still be insingleTaskAn instance oftaskIn the.
  3. Life cycle: sameSingleTopPattern one is the same. Just another pullbackActivityIn theonNewIntentmethods

  1. For example:ActivityThe stack has thisABtwoActivity. At this timeBIs at the top of the stack and the boot mode isSingleTaskMode. inB ActivityTo add a click event, you need to jump toC Activity. The result is to create a new oneC ActivityPut it on top of the stack.

Situation two: YesC ActivityTo add a click event, need to jump to anotherC Activity. The result isC ActivityThe aboveDDestruction,C ActivityBecome the top of the stack.

  • SingleInstancePattern (single instance pattern)
  1. Description:SingleInstanceIn particular, it is the global singleton pattern, which is an enhancedSingleTaskMode. 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 onetaskIn thetaskThere is only one instance, and nothing else is allowedActivityThere is.
  2. This is often used in system applications such asLaunch, 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. Example: For exampleA ActivityYes mode, startAAfter. The system creates a separate task stack for it due to the nature of in-stack reuse. Possible requests will not create new onesActivityUnless 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. Limited scope: the first way cannot beActivitySpecified directlyFLAG_ACTIVITY_CLEAR_TOPIdentification, the other way does not workActivityThe specifiedsingleInstanceMode.

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:

  • In the code aboveCourseDetailActivityThe startup mode is set in the configuration fileSingleTopMode, according to the introduction of the above startup mode, whenCourseDetailActivityAt the top of the stack.
  • Jump to the page againCourseDetailActivityWill just reuse the originalActivityAnd 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 callbackOnNewIntent (Intent Intent)Methods. This method passes in the latestintentIn 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 inActivityonCreateMethod to perform too many heavy operations, and inonPasueMethods 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 exampleFLAG_ACTIVITY_NEW_TASKFLAG_ACTIVITY_SINGLE_TOPAnd so on. It can also affectActivityThe operating state of, for exampleFLAG_ACTIVITY_CLEAN_TOPFLAG_ACTIVITY_EXCLUDE_FROM_RECENTSAnd 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
  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.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

  • 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

  • ActivityonSaveInstanceState()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 pressHomeKey) is destroyed by the systemActivityonSaveInstanceState()Will be called.
  • But when the user takes the initiative to destroy oneActivityFor example, press the back key in the application,onSaveInstanceState()It won’t get called.
  • Unless theactivityNot 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 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

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 abstraction (abstract class) class,AndroidA 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 applicationActivitySend 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 withActivity(onResume()
  • When aServiceThe binding is interactingActivity
  • Be actively called to the foregroundService(startForeground()
  • 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

  • The service process is throughstartService()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 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 as acacheTo increase the speed of the next startup of the component. The system process kills these processes in order to processcacheAnd the underlying kernelcacheBalance the entire system resources between.
  • androidThe 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

  • 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