Activity of four Android Components

Source: Internet
Author: User

Activity of four Android Components

Android Developers do not know the Activity. The Activity is the most frequently encountered and most frequently used component by developers. Here we will summarize some less frequently used knowledge.

Activity Lifecycle

Reference Block content

Key Points

OnStart (), onResume () is visible; onPause () is visible; others are invisible; onSaveInstanceState is saved; onRestoreInstanceState is restored; Activity is started

Activity can be started in four ways:

Standard singleTop singleTask singleInstance

Standard: Default mode. You do not need to write the configuration. In this mode, a new instance is created by default. Therefore, in this mode, you can have multiple identical instances and multiple identical activities.

SingleTop: You can have multiple instances, but do not allow the superposition of multiple identical activities. That is, if an Activity starts the same Activity at the top of the stack, the onNewIntent method is called instead of creating a new instance.

For example, if I have two activities named B1 and B2 with identical functions, both of them can jump to B1 or B2. The only difference is that B1 is standard and B2 is singleTop.
If the order of opening intention is B1-> B2-> B2, the actual opening order is B1-> B2 (the next attempt to open B2, actually, only the previous onNewIntent method is called)
If the order in which I open the intent is B1-> B2-> B1-> B2, the actual opening order is the same as that in which I open the intent. It is B1-> B2-> B1-> B2.

SingleTask: There is only one instance. If the Activity does not exist when you start the Activity in the same application, a new instance is created in the current task. If the Activity exists, the destory of other activities in the task is deleted and its onNewIntent method is called. If you start it in another application, a new task is created and the Activity is started in the task. singleTask allows other activities to coexist with it in a task. That is, if I open a new Activity in this singleTask instance, the new Activity will still be in the task of the singleTask instance.

For example:
If three of my applications, C1, C2, and C3, can start each other, And C2 is in singleTask mode, no matter how I click Start in this program, such as: C1-> C2-> C3-> C2-> C3-> C1-C2, C1, C3 may have multiple instances, however, C2 only exists, and all three activities are in the same task.
But C1-> C2-> C3-> C2-> C3-> C1-C2, this operation process should actually be as follows, because singleTask will remove other Activity destory on the task.
Operation: c1-> C2 C1-> C2-> C3 C1-> C2-> C3-> C2 C1-> C2-> C3-> C2-> C3-> C1 C1-> c2-> C3-> C2-> C3-> C1-C2
Actual: C1-> C2 C1-> C2-> C3 C1-> C2 C1-> C2-> C3-> C1 C1-> C2

If another application opens C2, a new task is started.
For example, if another application Other has an activity whose taskId is 200 and C2 is opened from it, the taskIdI of C2 is not 200. For example, the taskId of C2 is 201, if C1 and C3 are enabled from C2, The taskId of C2 and C3 is still 201.
Note: If you click home and then open Other, you will surely see content in the Other application instead of one of C1 C2 C3 in our application.

SingleInstance: There is only one instance, and this instance runs independently in one task. This task only has this instance and other activities are not allowed to exist.

For example:
The program has three ActivityD1, D2, and D3 activities that can start each other. D2 is in singleInstance mode. If the program runs from D1 and the taskId of D1 is 200, When D2 is started from D1, D2 starts a new task, that is, D2 and D1 are not running in one task. Suppose that the taskId of D2 is 201, and when D3 is started from D2, The taskId of D3 is 200, that is, it is pressed to the task stack started by D1.

If D2 is enabled in another application, assuming that the taskId of Other is 200 and D2 is enabled, D2 creates a new task to run and assumes that its taskId is 201, if D1 or D3 is started from D2 at this time, another task is created. Therefore, if the operation is other-> D2-> D1, this process involves three tasks.

Activity Parameters

Intent transfer parameter type:
Boolean,Char,Byte,Double,Float,Int,Long,ShortBasic data types and their Arrays
CharSequence/CharSequence [],String/String [],Bundle
And implementedSerializableOrParcelableObject

Serializable: Provided by java. All classes that implement Serializable are Serializable classes. No implementation is required.
Parcelable: androidSpecial and efficient. Rewrite requiredWriteToParcel ()

Principles for selecting serialization Methods

When using the memory,ParcelableRatioSerializableHigh performance, so it is recommended to useParcelable.

SerializableDuring serialization, a large number of temporary variables are generated, resulting in frequent GC.

ParcelableIt cannot be used when you want to store data on a disk, becauseParcelableThe data continuity cannot be well guaranteed in the case of external changes. AlthoughSerializableLow efficiency, but we recommend that you useSerializable.

Steps for implementing Parcelable

Implements Parcelable

Override the writeToParcel method to serialize your object into a Parcel object, that is, write the data of the class to the external provided Parcel, and package the data to be transferred to the Parcel container for storage, to get data from the Parcel container

Override the describeContents method. content interface description. By default, 0 is returned.

Instantiate static internal Object CREATOR implementation interface Parcelable. Creator

For example:

public class MyDemo implements Parcelable {    private int mData;    private int mHaha;    public int describeContents() {        return 0;    }    public void writeToParcel(Parcel out, int flags) {        out.writeInt(mData);        out.writeInt(mHaha);    }    public static final Parcelable.Creator
  
    CREATOR = new Parcelable.Creator
   
    () {        public MyDemo createFromParcel(Parcel in) {            return new MyDemo(in);        }        public MyDemo[] newArray(int size) {            return new MyDemo[size];        }    };    private MyDemo(Parcel in) {        mData = in.readInt();        mHaha = in.readInt();    }}
   
  
Acivity configChanges attributes

It is generally not used in the AndroidManifest. xml file.Android: configChanges= "Orientation | screenSize" configuration, of course, is very useful.
That is, if this attribute is configured, it will be called directly when we switch between the portrait and landscape screens.OnCreateMethodOnConfigurationChangedInstead of re-runningOnCreateMethod, of course, if this attribute is not configured, it will be called againOnCreateMethod

Android: configChanges = ["Mcc","Mnc","Locale",
"Touchscreen","Keyboard","KeyboardHidden",
"Navigation","ScreenLayout","FontScale","UiMode",
"Orientation","ScreenSize","SmallestScreenSize"]

Mcc:The IMSI mobile country code (MCC) has changed-a SIM has been detected and updated the MCC.
IMSI (International Mobile User Identification Code) changed, detected SIM card, or updated MCC Mnc:The IMSI mobile network code (MNC) has changed-a SIM has been detected and updated the MNC.
IMSI network changed, SIM card detected, or MCC updated
The mcc and mnc cannot be changed theoretically. Locale:The locale has changed-the user has selected a new language that text shoshould be displayed in.
When the language changes, the user selects a new language and the text should be re-displayed. Touchscreen:The touchscreen has changed. (This shoshould never normally happen .)
The touch screen is changed, which should not happen normally. Keyboard:The keyboard type has changed-for example, the user has plugged in an external keyboard.
The keyboard type is changed. for example, if you use an external keyboard ** keyboardHidden: ** the keyboard accessibility has changed-for example, the user has revealed The hardware keyboard.
The keyboard is changed. For example, the user uses a hardware keyboard.
Navigation:The navigation type (trackball/dpad) has changed. (This shoshould never normally happen .)
Navigation changes (this should not happen normally). For example, connecting to a Bluetooth keyboard does change the type of navigation. After connecting to the Bluetooth keyboard, I can use the direction key to navigate. ScreenLayout:The screen layout has changed-this might be caused by a different display being activated.
The screen layout changes, which may lead to activation of different displays. FontScale:The font scaling factor has changed-the user has selected a new global font size.
The global font size scaling has changed. Orientation:The screen orientation has changed-that is, the user has rotated the device. device rotation, horizontal display and vertical display mode switch. ScreenSize:Screen size changed SmallestScreenSize:The physical size of the screen has changed, for example, connecting to an external screen. LayoutDirectionAttribute (). When the language settings are changed, the attribute will also be a mask bit in newConfig. Therefore, when determining whether to restart the Activity, ActivityManagerService (actually in ActivityStack) always determines whether to restart the Activity.
Add locale and layoutDirection in android: configChanges.
If you do not exit the application, switch to the Settings to switch the language and find that the Activity is restarted. Activity windowSoftInputMode

WindowSoftInputModeIs used to set the interaction mode of the window keypad. The attribute has a total of nine values:

StateUnspecified,StateUnchanged,StateHidden,StateAlwaysHidden,StateVisible,StateAlwaysVisible,AdjustUnspecified,AdjustResize,AdjustPan.

StateUnspecified
The status is not specified.Android: windowSoftInputModeThis interaction mode is used by the software by default. The system uses the display mode of the soft keyboard based on the interface. For example, when there are only texts and buttons on the interface, the Soft Keyboard will not pop up automatically, because there is no need to input. Then, when an input box for getting the focus is displayed on the interface and the stateUnspecified attribute is set, the soft keyboard is not displayed by default, however, when the UI of an input box with a focus needs to scroll, a soft keyboard is automatically displayed. Why do you need to emphasize the input box for getting the focus? If the focus is not obtained from the input box, the keyboard will not pop up automatically, so that one solution of the Soft Keyboard will not pop up automatically on the interface, in the xml file, set a non-input box control to get the focus, so as to prevent the keyboard from popping up.

StateUnchanged
Chinese means that the State does not change. How should we understand this sentence? In fact, it is easy to understand, that is, the current interface's soft keyboard status depends on the soft keyboard status of the previous interface. For example, if the current interface keyboard is hidden, the interface after the jump is also hidden; if the current interface is displayed, the interface after the jump is displayed, the keyboard is also displayed.

StateHidden
As the name suggests, if we set this attribute, the keyboard status must be hidden. No matter what the status of the previous interface is or whether there is any input requirement on the current interface, it is not displayed. Therefore, we can set this attribute to control the non-automatic pop-up of the keyboard.

StateAlwaysHidden
When the main Activity window gets the focus, the keyboard is always hidden.

StateVisible
Set this attribute to summon the soft keyboard, even if there is no input box on the interface, it can be forcibly summoned.

StateAlwaysVisible
This property can also summon the keyboard, but it is slightly different from the stateVisible property. For example, when we set it to the stateVisible attribute, if the current interface keyboard is displayed, when we click the button to jump to the next interface, the keyboard is hidden because the input box loses its focus. When we return to the current interface again, the keyboard is hidden. But if we set stateAlwaysVisible, we will jump to the next interface, and the soft keyboard will be hidden. But when we come back, the soft keyboard will be displayed. Therefore, this Always explains the difference. The soft keyboard displays the status no matter when the current interface is reached (normal jump or the previous interface is returned by the user.
Speaking of this, I think of the above stateHidden and stateAlwaysHidden. I guess the same is true. That is to say, stateAlwaysHidden is hidden in any way, but if you jump to the next interface, when the soft keyboard is summoned, the keyboard will not be hidden when the current interface is returned by the user. However, I have not found a way to jump to the next interface, this method does not disappear the keyboard of the current interface, so it cannot be verified for the time being.

AdjustUnspecified
Starting from this attribute, it is not to set the display and hide modes of the soft keyboard, but to set the display relationship between the soft keyboard and the display content of the software. When you do not set this value with us, this option is also the default setting mode. In this case, the system selects different modes based on the interface. If the interface contains a control that can be rolled, such as ScrowView, the system will reduce the size of the interface that can be rolled, so that all content can be seen even if the keyboard is displayed. If there is no scroll control in the layout, the keyboard may cover some content.

AdjustResize
This attribute indicates that the main window of the Activity is always adjusted to ensure the space displayed on the keyboard.

AdjustPan
The content of the current window is automatically moved so that the current focus is not overwritten by the keyboard and the user can always see the part of the input content.

Activity switching animation code
overridePendingTransition(R.anim.scale, R.anim.alpha)
Xml file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.