[Android] Do you really know anything about activity?

Source: Internet
Author: User

What is activity?

We all know that there are four components in Android (activity, service, Content Provider, Broadcastreceiver broadcast receivers), activity is the most and most basic component we use, Because all the actions of the app are user-related, the Activity provides a window to interact with the user.
Official documents so to speak:
  

An activity was a single, focused thing that the user can do. Almost all activities interact with the user, and the Activity class takes care of creating a window for you in which C A place your UI with Setcontentview (View).

The approximate meaning (forgive me):

Activity is independent and equal to the handling of user operations. Almost all activity is used to interact with the user, so the activity class creates a window where the developer can put the UI onto the window via the Setcontentview (View) interface.

Activity in Android is all attributed to task management. A task is a collection of multiple activity that is queued to a stack (that is, "back stack") in the boot order. Android By default maintains a task for each app to hold all of the app's activity,task default name for the app's PackageName.

Of course, we can also declare the activity's Taskaffinity property in Androidmainfest.xml to customize the task, but it is not recommended, and if other apps also declare the same task, it's possible to launch into your activity, bringing security issues (such as getting your Intent).

Internal call procedure for activity

As stated above, the system manages activity through the stack, when a new activity starts, it is placed on top of the stack and becomes run activity, the previous activity is always kept below it on the stack, and does not reach the foreground again until the new event exits.

Or on this official website of the Activity_lifecycle map:
   

    • When you first open a new activity instance, the system calls

OnCreate (), OnStart (), Onresume () and then start running

Running is overwritten (it opens a new activity or is locked, but it is still running in the foreground , lost focus is still visible), the system calls OnPause ();

The method performs activity pauses, which are typically used to commit unsaved changes to persisted data, stop animations, and other things. But this activity is still completely alive (it keeps all the state and member information and remains connected to the window manager )

And then it has three ways out.
The ① user returns to the activity and calls the Onresume () method again running

② the user returns to the desktop or opens other activity, it calls OnStop () into the Stop state (all state and member information is kept, not visible to the user )

③ the system is out of memory, and a higher-power application requires memory, the activity's process may be reclaimed by the system. (Reclaim Onrause () and OnStop () status of the activity process) to re-open it must be recreated again.

If the user returns to the activity in the OnStop () state (which is also displayed in the foreground), the system calls

Onrestart (), OnStart (), Onresume () and then re-running

The OnDestroy () method is called before the activity finishes (call Finish ()) or killed by the system to release all the resources that are occupied.

Three nested loops in the activity life cycle

    • The full lifetime of the activity occurs between the OnCreate () call and the OnDestroy () call.

    • The visible lifetime of the activity occurs between the OnStart () call and the OnStop () call. The system calls OnStart () and OnStop () multiple times throughout the lifetime of the activity, as activity may be constantly switching back and forth between display and hide.

    • The front and rear transitions of the activity occur between the Onresume () call and the OnPause ().
      Because this state can occur frequently, the code in both methods should be fairly lightweight in order to avoid user waits caused by switching delays.

Status and information preservation and recovery process of activity being recycled
 Public  class mainactivity extends Activity {    @Override    protected void onCreate(Bundle savedinstancestate) {if(savedinstancestate!=NULL){//To determine if there are previous saved state informationSavedinstancestate.get ("Key"); }Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_main); }@Overrideprotected void onsaveinstancestate(Bundle outstate) {//TODO auto-generated method stub     //May be reclaimed memory before saving state and information,Bundle data =NewBundle (); Data.putstring ("Key","Last words before is Kill"); Outstate.putall (data);Super. Onsaveinstancestate (outstate);}@Overrideprotected void onrestoreinstancestate(Bundle savedinstancestate) {//TODO auto-generated method stub       if(savedinstancestate!=NULL){//To determine if there are previous saved state informationSavedinstancestate.get ("Key"); }Super. Onrestoreinstancestate (Savedinstancestate);}}

Onsaveinstancestate method

Called before the activity may be recycled to save its own state and information so that it recovers data when rebuilt (in OnCreate () or onrestoreinstancestate ()). Rotating the screen rebuild activity calls the method, but other situations in the Onrause () and OnStop () States are not necessarily called, and the following is a document description of the method.

One example ofWhen OnPause andOnStop isCalled and  notThis method isWhen a user navigates Back  fromActivity B toActivity A:There isNo need toCall Onsaveinstancestate onB because thatParticular instance'll never be restored, so theSystem avoids callingit. An example when OnPause isCalled and  notOnsaveinstancestate isWhen Activity B isLaunchedinch Front  ofActivity A: theSystem may avoid calling Onsaveinstancestate onActivity Aif it isn ' tKilled during theLifetime ofBsince  theState of  theUser interface ofA'll stay intact.

That is, the system is flexible enough to decide not to call the method, but if the call must occur before the OnStop method, it is not guaranteed to occur before or after the OnPause.

Onrestoreinstancestate method

This method is called between OnStart and Onpostcreate, and can be restored in OnCreate, but it is sometimes necessary to restore the state after all layout initialization is complete.

Onpostcreate: Generally do not implement this method, when the code of the program starts to run, it calls the system to do the final initialization work.

Startup mode startup mode what?

  
In short, you define how the activity instance is associated with a task.
  

Why do you define a startup mode?

In order to implement some requirements other than the default boot (standard) mode:
  

    • Let an activity start a new task (instead of being put into the current task)

    • Let activity start by simply calling out an existing instance (rather than creating a new instance at the top of the back stack)

    • Or, you want to keep only the root activity when the user leaves the task, and the rest of the activity in the back stack is emptied

How do I define the startup mode?

There are two ways to define the startup mode:

Using the manifest file

When the activity declaration is made in the manifest file, the activity element's Launchmode attribute is used to set the relationship between the interaction and the task.

<activity            ......            android:launchMode="standard"             >           .......        </activity>

Note: The mode you set for activity with the Launchmode property can be overridden by the intent flag that initiates the activity.

What are the startup modes?
    • "Standard" (default mode)

      When the activity is started by this mode, Android always creates a new instance of the target activity and adds that activity to the current task stack. This method does not start a new task, but adds the new activity to the original task.
        

    • "Singletop"

      This pattern is basically the same as standard mode, but it is different: when the activity that is going to be started is already at the top of the task stack, the system does not recreate the target activity instance, but instead directly reuse the activity at the top of the task stack.

    • "Singletask"

      Activity has only one instance within the same task.
        
      If the activity that will be started does not exist, then the system will create the instance and add it to the top of the task stack;

      If the activity that is about to start already exists, and there is a stack top, directly reuse the activity at the top of the task stack.

      If the activity exists but is not at the top of the stack, then all other activity on top of the activity is moved out of the task by the system so that the target activity is at the top of the stack.

    • "SingleInstance"

      Regardless of the task from which the target activity is started, only one target activity instance is created and the activity instance is loaded with a completely new task stack (global singleton).

      If the activity to be started does not exist, the system will first create a completely new task and then create the target activity instance and put the activity instance into this new task.

      If the activity that is about to be started already exists, then no matter which application it is in, which task it is in, the system will move the activity's task to the foreground so that the activity is displayed.

Using the Intent flag

In order to start the activity, you can change the default relationship between activity and task by including the corresponding flag in the intent passed to StartActivity ().

new Intent(this,NewActivity.class);        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        startActivity(i);
What are the default modes that can be modified by flags?
    • Flag_activity_new_task

      The activity is started in the new task in the same way as the "Singletask" mode. If the activity you want to start is already running in a task, that task will be transferred to the foreground.

    • Flag_activity_single_top

      As with the "singletop" mode, if the activity to be started is at the top of the back stack, the target activity instance is not recreated and the activity at the top of the task stack is directly reused.

    • Flag_activity_clear_top

        This mode does not have a corresponding attribute value in Launchmode. if the activity to be started is already running in the current task, a new instance is no longer started, and all activity above it will be destroyed.

Some suggestions on the startup mode

Generally do not change the way activity and task work by default. If you are sure you need to modify the default mode, be cautious and make sure that activity is more testing and security-related work when it starts and returns from other activity.

Intent Filter

Android's 3 core components,--activity, services, broadcast receivers--pass messages through intent. Intent messages are used to bind different components at run time.
In Android's androidmanifest.xml configuration file, you can specify its intent filter for an activity via the Intent-filter node to tell the system what type of intent the activity can respond to. 。

Three properties of Intent-filter action

A Intent Filter can contain multiple action,action lists to indicate the "action" that the activity can accept, which is a user-defined string.

<intent-filter >  <action android:name="android.intent.action.MAIN" />  <action android:name="com.scu.amazing7Action" /></intent-filter>

You can start the intent object by using the following statement in your code:

Intent i=new Intent(); i.setAction("com.scu.amazing7Action");

Activity that contains "Com.scu.amazing7Action" in the Action list will match successfully

Url

In the Intent-filter node, the external data is matched through the data node, that is, the external data is carried by the URI to the target component.

<data android:mimeType="mimeType"     android:scheme="scheme"      android:host="host"     android:port="port"      android:path="path"/>

Note: URI data matching succeeds only if all properties of data match successfully

Category

Defines a list of categories for the component that will be successful if all of the items in this category list are included in the Intent.

<intent-filter . . . >   <action android:name="code android.intent.action.MAIN" />   <category android:name="code android.intent.category.LAUNCHER" /></intent-filter>
The matching process of Activity species Intent Filter

① Loading all Intent filter lists
② Remove the intent Filter for which the action match failed
③ Remove the intent Filter that failed the URL match
④ Remove Intent Filter for category match failure
⑤ determines whether the remaining intent filter number is 0. If an exception is returned for a 0 lookup failure, or if it is greater than 0, sort by priority, returning the highest priority intent Filter

Some problems of activity in development
    • General settings activity is non-public

<activity  ...... android:exported="false" />

Note: Non-public activity cannot set Intent-filter to avoid being woken up by other activity (if you have the same intent-filter).

    • Do not specify the activity's Taskaffinity property

    • Do not set the activity's Launchmode (keep default)

      Note that the intent of ACTIVITY should not be set to Flag_activity_new_task

    • When using this in an anonymous inner class, add the Activity class name (class name. This, not necessarily the current activity)

    • Set Activity Full Screen

      In its onCreate () method, add:

// 设置全屏模式 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);  // 去除标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE);

Feel helpful, top, thank you!

[Android] Do you really know anything about activity?

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.