Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the life cycle of Android

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "what is the life cycle of Android?", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what is the life cycle of Android" article.

0. Overall architecture of Android

Talk about your understanding of android system (system) architecture.

Linux operating system as the core, from the bottom up, dependency.

Application layer: including system applications and third-party applications.

Application framework: provide some API frameworks necessary for application development, which is an important means of software reuse.

Libraries: android Runtime (core packages (equivalent to packages provided by JDK), virtual machines (optimized JVM); some libraries of Calgary +

Linux core: provides core system services such as power management, process scheduling, memory management, network protocol stack, driver model, etc.

Four components of android and their Application scenarios

Activity: the component responsible for interacting with users in Android applications.

Service: often used to provide background services for other components or to monitor the running status of other components. It is often used to perform time-consuming operations.

BroadcastReceiver: used to listen to other components in the application.

Real-time data exchange between ContentProvider:Android applications.

1. The life cycle of Activity

Life cycle: when the object is born, when it dies, how to write the code, where the code is written.

Note:

When a new Activity is opened and the transparent theme is adopted, the current Activity will not call back the onStop

OnCreate and onDestroy pairing, onStart and onStop pairing (visible), onResume and onPause pairing (whether it is in the foreground, can interact with the user)

When you open a new Activity, the relevant Log is:

Main1Activity: onPause Main2Activity: onCreate Main2Activity: onStart Main2Activity: onResume MainA1ctivity: onStop

Life cycle in an abnormal state:

Resource-related system configuration changes or insufficient resources: for example, if the screen is rotated, the current Activity will be destroyed, and the onSaveInstanceState will be called back before onStop to save the data, and the onRestoreInstanceState will be called back after onStart when the Activity is recreated. Where Bundle data is passed to onCreate (not necessarily data) and onRestoreInstanceState (there must be data).

To prevent rebuilding when the screen is rotated, add the configuration to the manifest file:

Android:configChanges= "orientation"

2. The life cycle of Fragment

Normal start

Activity: onCreate Fragment: onAttach Fragment: onCreate Fragment: onCreateView Fragment: onActivityCreated Activity: onStart Activity: onResume

Normal exit

Activity: onPause Activity: onStop Fragment: onDestroyView Fragment: onDestroy Fragment: onDetach Activity: onDestroy

3. The startup mode of Activity

Standard: each time Activity is activated (startActivity), an instance of Activity is created and placed on the task stack

SingleTop: if an Activity activates itself, that is, the Activity is at the top of the task stack, you do not need to create it. In other cases, you need to create an Activity instance.

SingleTask: if the Activity you want to activate has this instance in the task stack, you don't need to create it, just put the Activity at the top of the stack, that is, pop all the Activity instances above the Activity and call its onNewIntent.

SingleInstance: a MainActivity instance has been created in the task stack of App 1. If App 2 also wants to activate MainActivity, there is no need to create it. The two applications share the Activity instance.

4. The value passed between Activity and Fragment

Through findFragmentByTag or getActivity to get each other's reference (strong turn), and then call each other's public method, but to do so is to introduce a "strong turn" of the ugly code, the other two classes hold each other's strong reference, the coupling is large, easy to cause memory leaks.

Pass the value through the method of Bundle, such as the following code:

/ / set some parameters fragment.setArguments (bundle) for fragment in Activity; / / get the method Bundle arguments = getArguments () in Activity through getArguments in fragment

Using eventbus for communication, this method has high real-time performance, and the Activity and Fragment can be completely decoupled.

The code in / / Activity EventBus.getDefault () .post ("message"); / / the code in Fragment EventBus.getDefault () .register (this); @ Subscribe public void test (String text) {tv_test.setText (text);}

5 、 Service

There are two types of Service:

The local service, which belongs to the same application, is started by startService or bound and obtained by bindService. If you just want to set up a service to run in the background, you can directly startService. If you need to pass values or operations to each other, you should use bindService.

Remote services (between different applications) that bind and get proxy objects through bindService.

The corresponding life cycle is as follows:

Context.startService ()-> onCreate ()-> onStartCommand ()-> Service running-- call context.stopService ()-> onDestroy () context.bindService ()-> onCreate ()-> onBind ()-> Service running-- call > onUnbind ()-> onDestroy ()

Be careful

Service runs on main threads by default, so if you need to perform time-consuming operations in Service (operations on large files, copies of databases, network requests, file downloads, etc.), they should be done in child threads.

! The special case is that Service specifies in the manifest file to run in other processes.

6. Message passing mechanism in Android

Why use Handler?

Because the screen is refreshed at a frequency of 60Hz, about once every 16 milliseconds, in order to ensure the fluency of UI, time-consuming operations need to be handled in child threads, which cannot update UI directly. Therefore, Handler is required to send a message to the main thread in the subthread to update the UI.

A little further here, the UI control in Android is not thread-safe, so it can cause the UI control to be in an unpredictable state when multiple threads access the UI concurrently. Google does not deal with this problem through the locking mechanism because:

The introduction of locks will complicate the operation of UI.

The introduction of locks will reduce the running efficiency of UI.

Therefore, Google engineers operate UI through a single-threaded model, and developers only need to cut flowers between different threads through Handler.

An overview of the messaging mechanism in Android?

The message mechanism in Android mainly refers to the running mechanism of Handler. Handler is the key to thread switching, and switching between main threads and child threads is just a special usage scenario. The things that the messaging mechanism needs to know are the MessageQueue objects in Message, Handler, Looper, and Looper.

As shown in the figure above, we can think of the entire messaging mechanism as a pipeline. Where:

MessageQueue is the conveyor belt and is responsible for the transmission and management of Message queues.

Looper is the engine of the pipeline, constantly taking messages out of the message queue and handing them over to Handler for processing.

Message is every product.

Handler is a worker. But this analogy is not appropriate, because it is Handler that sends and ultimately processes the Message.

Why does creating a Handler in a child thread throw an exception?

The work of Handler depends on Looper, while Looper (and message queuing) belongs to a thread (ThreadLocal is a data storage class within a thread through which data can be stored in a specified thread and cannot be accessed by other threads), and cannot be accessed by other threads. So the Handler is indirectly bound to the thread. So to use Handler, you must make sure that the thread created by Handler has a Looper object and starts the loop. Because there is no Looper by default in the child thread, an error will be reported.

The correct way to use it is:

Handler = null; new Thread (new Runnable () {private Looper mLooper) @ Override public void run () {/ / you must call the prepare method of Looper to create a Looper object for the current thread, and then start the loop / / prepare method which essentially creates a Looper object for the ThreadLocal object / / if the current thread has already created a Looper object, it will report an error Looper.prepare (); handler = new Handler () / / get the Looper object mLooper = Looper.myLooper (); / / start the message loop Looper.loop (); / / exit the Looper message loop when appropriate to prevent memory leaks mLooper.quit ();}}) .start ()

The Looper is created and the message loop is started by default in the main thread, so there is no error:

The entry to the application is the main method of ActivityThread, where the Looper is created and the loop method of Looper is executed to start the message loop so that the application runs all the time.

Can a child thread send a message to the main thread through Handler?

Sure. Sometimes, for business needs, the main thread can send messages to child threads. The Handler of the child thread must be created as described above and associated with the Looper.

7. Event delivery mechanism and custom View related

View tree of Android

The mechanism of View in Android is mainly the display of Activity. Each Activity has a Window (the implementation class in the mobile phone is PhoneWindow). Under Window, there are TitleVie and ContentView under DecorView,DecorView, and ContentView is specified by setContentView in Activity.

Event transmission and distribution mechanism

ViewGroup has the following three methods for event distribution, while View has only dispatchTouchEvent and onTouchEvent.

@ Override public boolean dispatchTouchEvent (MotionEvent ev) {return super.dispatchTouchEvent (ev);} @ Override public boolean onInterceptTouchEvent (MotionEvent ev) {return super.onInterceptTouchEvent (ev);} @ Override public boolean onTouchEvent (MotionEvent event) {return super.onTouchEvent (event);}

Events are always distributed from top to bottom, that is, first to Activity, then to ViewGroup, then to sub-View, and if there are no view consumption events, events are passed back along the path. Where:

DispatchTouchEvent is the event distribution method, if the event can reach the view, it will be called first, usually we do not modify this method.

OnInterceptTouchEvent is the core method of event distribution, indicating whether the ViewGroup intercepts the event. If true is returned, the onTouchEvent of the ViewGroup will be called and the event will not be passed down.

OnTouchEvent is * level, and * is called in event distribution.

The child View can ask the parent element not to intercept through the requestDisallowInterceptTouchEvent method.

Be careful

Events are passed from Activity.dispatchTouchEvent () and all the way down (child View) from the uppermost View (ViewGroup) as long as they are not stopped or intercepted. The child View can handle the event through onTouchEvent ().

Events passed by the parent View (ViewGroup) to the child View,ViewGroup can be intercepted by onInterceptTouchEvent () and stopped passing down.

If the event has not been stopped from top to bottom, and there is no consumption event in the layer View, the event will be passed upwards in reverse. In this case, the parent View (ViewGroup) can consume it. If it is still not consumed, * will go to the onTouchEvent () function of Activity.

If View does not consume ACTION_DOWN, other events that follow will not be passed.

OnTouchListener takes precedence over onTouchEvent () to consume events.

Customize the classification of View

Extend existing subclasses of View, such as overriding onDraw methods, extending new functions, and so on.

Custom composite controls, combining some commonly used controls for ease of use.

Directly inheriting View to realize the complete customization of View, it is necessary to complete the measurement and drawing of View.

Custom ViewGroup, need to copy the onLayout to complete the determination of the location of the sub-View and other work.

Measurement of View-onMeasure

The final measurement of View is to set the two MeasureSpec representing width and height to View through setMeasuredDimension in the onMeasure method, so it is necessary to master MeasureSpec. MeasureSpec includes size information as well as schema information.

Three modes of MeasureSpec:

EXACTLY mode: precise mode, corresponding to when the user specifies as match_parent or a specific size (in fact, specifying as match_parent essentially specifies the size as the size of the parent container)

AT_MOST mode: corresponding to the wrap_content specified by the user, the size of the control does not exceed the allowed size of the parent control.

UNSPECIFIED mode: measurement mode that does not specify a size, which is rarely used

Here is the template code:

Public class MeasureUtils {/ * Measurement for View * * @ param measureSpec * @ param defaultSize * @ return * / public static int measureView (int measureSpec, int defaultSize) {int measureSize; / / get the size specified by the user and the mode int mode = View.MeasureSpec.getMode (measureSpec) Int size = View.MeasureSpec.getSize (measureSpec); / / return size if according to mode (mode = = View.MeasureSpec.EXACTLY) {/ / precise mode (specify size and match_parent) directly return specified size measureSize = size } if else {/ / UNSPECIFIED mode, AT_MOST mode (wrap_content), the default size measureSize = defaultSize is required. In if (mode = = View.MeasureSpec.AT_MOST) {/ / AT_MOST (wrap_content) mode, you need to take the minimum measured value and default value measureSize = Math.min (measureSize, defaultSize);}} return measureSize;}}

*, copy the onMeasure method and remove the super method:

@ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {setMeasuredDimension (MeasureUtils.measureView (widthMeasureSpec, 200), MeasureUtils.measureView (heightMeasureSpec, 200);}

Drawing of View-onDraw

To draw View, you need to master the coordinate system of View in Android:

The coordinate system of View takes the upper left corner as the origin, the right direction is the positive direction of X axis, and the downward direction is the positive direction of Y axis.

View rendering is mainly done through the 2D drawing mechanism of Android, and the timing is in the onDraw method, including canvas Canvas and brush Paint. Let's show you the example code. The relevant API is not the focus of the introduction, the focus is on the save and restore methods of Canvas. After save, you can zoom in, rotate, tilt and other operations on the canvas. These two methods are generally used together, in which save can be called more often than restore.

@ Override protected void onDraw (Canvas canvas) {super.onDraw (canvas); Bitmap bitmap = ImageUtils.drawable2Bitmap (mDrawable); canvas.drawBitmap (bitmap, getLeft (), getTop (), mPaint); canvas.save (); / / Note that the rotation here refers to the rotation of the canvas canvas.rotate (90); mPaint.setColor (Color.parseColor ("# FF4081")); mPaint.setTextSize (30) Canvas.drawText ("Test", 100,100, mPaint); canvas.restore ();}

Related to the layout location is the copy of the onLayout method. In general, when we customize the View, we only need to complete the measurement and drawing. If you are customizing ViewGroup, all you need to do is measure yourself and control the layout position of child controls in onLayout. OnLayout is a method that must be implemented in custom ViewGroup.

8. Performance optimization

Layout optimization

Using the include tag, reuse the same layout through the layout attribute.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report