Android four components fully resolved (i)---Activity

Source: Internet
Author: User

This article refers to the class annotations in the \android\android\frameworks\base\core\java\android\app\activity.java file, as well as the Android/frameworks/base/docs /HTML/GUIDE/COMPONENTS/ACTIVITIES.JD file

One activity profile:

Activity is a separate thing that can interact with the user. Almost all activities interact with the user, so the activity takes on the task of creating the window, and you can fill the view in the window with a Setcontentview method. Via a Theme properties Android. R.attr#windowisfloating to set Activities is full screen display full-screen or hover window isfloat (such as dialog, or a suspended view), of course, the full-screen display does not include the status bar.

<!-- 全屏显示  --><item name="windowIsFloating">false</item>

There are dialog theme styles in the corresponding topic.

<!-- 悬浮窗显示 --><style name="Theme.Material.BaseDialog">‘‘‘‘‘‘ <item name="windowIsFloating">true</item> ‘‘‘‘‘‘ </style>

Two methods need to be implemented when inheriting activity

    • OnCreate: Initializes the activity in this method. More importantly, it is often necessary to call the Setcontentview method in the method to load the layout file and use Findviewbyid to retrieve the controls in the layout file that you want to interact with.
    • OnPause: This method is called when the user leaves the activity. Any modifications made by the user should commit a commit in the method (typically saving the submitted data using Android.content.ContentProvider).

In order to be able to open an activity using android.content.context#startactivity context.startactivity (), We need to declare activity in the Androidmanifest file under the corresponding package using the Activity node

<application android:icon="@drawable/icon"‘‘‘‘‘‘<!-- 声明activity --><activity android:name=".MainMenuActivity"‘‘‘‘‘‘</activity>‘‘‘‘‘‘</application>
The topics related to activity are
    • #Fragments
    • #ActivityLifecycle
    • #ConfigurationChanges
    • #StartingActivities
    • #SavingPersistentState
    • #Permissions
    • #ProcessLifecycle
One, Fragments:fragment introduction

Fragment starts at Android3.0 and is the fragment of the application component that can be placed inside the activity. Manage interactions with fragment through Fragmentmanager. Fragmentmanager objects can be obtained in two ways

    • Activity#getfragmentmanager () Activity.getfragmentmanager ()
    • Fragment#getfragmentmanager () Fragment.getfragmentmanager ()

The fragment class can be used to obtain a wide variety of results, within which it represents a common operation or interface. Fragment is closely linked to the activity that contains him, and fragment relies on activity. Although fragment has its own life cycle, the life cycle of fragment is closely related to the life cycle of the activity. The fragment life cycle diagram is as follows:

Fragment is attached to activity, and when activity is stopped, fragment in activity cannot be started. When the activity is destroyed, the fragment in the activity is destroyed as well.

All fragment subclasses must contain an argument-free construction method. When necessary, especially during the state recovery period, the framework layer will often reinitialize fragment,framework to find the parameterless constructor to initialize the fragment. If the fragment constructor is not available, the runtime exception is thrown when the state resumes.

Fragment Related topics are:
    • #OlderPlatforms旧版本
    • #Lifecycle生命周期
    • #Layout布局
    • #BackStack
Olderplatforms:

Fragment is in the Android3.0 only to join in, so before Android3.0 if you want to use fragment can use android.support.v4.app.FragmentActivity specific can refer to
Fragments for all

Lifecycle
    • #onAttach when fragment is called with activity binding
    • #onCreate called when fragment initialization is created
    • #onCreateView创建并返回与fragment相关的view视图
    • #onActivityCreated notify fragment that the activity it binds to has oncreate
    • #onViewStateRestored notifies fragment that the status of all view saved has been restored
    • #onStart fragment visible to the user
    • #onResume fragment is visible to the user and gets focus
    • #onPause fragment can no longer interact with the user (activity is paused or fragment action)
    • #onStop fragment is not visible to the user (activity is stopped or fragment action)
    • #onDestroyView Eliminate all views related to fragment
    • #onDestroy Clear Fragment Status
    • #onDetach called when fragment is unbound from activity
Layout

Fragment can be used as part of the application layout and can be better modularized with fragment,activity to create more complex user interactions for larger screens, enabling the application to switch between small screen and large screen sizes. For example, on an activity you can write a fragment with the item list, and then combine a fragment to display the details of each item.

<fragment            class="com.example.android.wifidirect.DeviceListFragment"            android:id="@+id/frag_list"            android:layout_width="match_parent"            android:layout_height="@dimen/phone_list_height">            <!-- Preview: [email protected]/row_devices -->        </fragment>

Fragment related can be consulted:
Fragment nesting
Fragment and activity

Two, activitylifecycle

In the system, activity is managed by a thing called the activity stack. When a new activity is created, it is placed on top of the stack and becomes a running activity--the previous activity is kept below the activity, and when the activity on the stack exits, Activity below the activity is run to the foreground, and the activity stack follows the principle of the stack: LIFO.

There are basically four states of an activity.

    1. Active/running: When the activity is on the front of the screen (at the top of the stack) we call him active or running.
    2. Paused: When the activity loses focus but is still visible to the user, it is called the paused state. In this case, there may be a transparent activity or a small size activity covering the activity. Activity in paused is also alive (the activity retains all state and member information and is still bound to wiindowmanager), but when memory is low, activity in the paused state is likely to be killed by the system
    3. Stopped: When an activity is completely covered by another activity, it is in stopped state. At this point, the activity is not visible to the user and has no focus, but all state and member information is still saved. When memory is needed elsewhere, the system will kill the activity in the stopped state.
    4. If the user is in the paused or stopped state, it is likely that the activity will be removed from memory by finish the activity or the kill process. When it is loaded again to the user, it must be restarted and restored to his previous state.

Next look at a flowchart of the Activity life cycle: (from source)

It's a very clear writing.
In this flowchart you can see that there are three key loops

    The full period of the
    1. entire lifetime:activity: From the first call of the activity to OnCreate to the last call to OnDestroy. The activity creates all the global state in the OnCreate method and frees all remaining resources in the OnDestroy () method. For example, if activity opens a network download process in the background, the activity opens the thread in the OnCreate method and stops the thread in the OnDestroy method.
    2. Visible Lifetime visibility period: Occurs between activity calls OnStart and OnStop. Activity is visible to the user during visibility, but may not be able to interact with the user in the foreground. Between these two methods, you can save the resources that the activity needs to show to the user. For example, you can register a broadcastreceiver in OnStart to monitor changes that affect the UI and unregister the broadcast in the OnStop method. The OnStart and OnStop methods can be called multiple times to make the activity visible or hidden.
    3. foreground lifetime foreground period: Activity calls Onresume start, until OnPause is called. During this time the activity is on top of all activity and can interact with the user. An activity can frequently switch between the resumed state and the paused state-for example, when the device sleeps, the activity is paused, So the Onresume and OnPause methods of activity should be some of the lightweight code .
publicclass MyActivity extends Activity{protectedvoidonStart//注册广播void//注销广播  mContext.unregisterReceiver(mReceiver); } }

The full life of the activity includes all of the following methods of activity. You can implement these methods to get the job done. All activity implements the OnCreate method to complete the initialization operation, and many activity implements the OnPause method to commit the data changes and prepare to stop user interaction. Methods of the parent class should be called when the method is being overwrite

 Public  class Activity extends applicationcontext{   protected void onCreate(Bundle savedinstancestate)protected void OnStart();protected void Onrestart();protected void Onresume();protected void OnPause();protected void OnDestroy();}

The switch between activity life cycle methods is shown in the following table

Method Description killable Next
OnCreate () Called when the activity is first created. In the OnCreate method, you need to do some static initialization operations: Create views, bind list data, and so on. If the bundle parameter passed by the OnCreate is not NULL, the previous state of the activity can be obtained from the bundle No OnStart
Onrestart () Called when the activity has been stopped but reloaded No OnStart
OnStart () Called when activity is visible to the user No If activity becomes the foreground activity, then the Onresume method is called. If activity is hidden hidden then the OnStop method is called
Onresume () This method is called when activity can begin with user interaction, where activity gets to focus. As the user enters, the activity is at the top of the stack. No OnPause
OnPause () Called when the system wants to get the focus of a previous activity. This method is often used to commit unsaved data, stop animations, and other things that consume CPU memory. The implementation of the method must be fast because the next activity will be resumed until the OnPause method executes and will remain blocked When activity returns to the foreground to the front, Onresume is called when the activity is not visible to the user invisible OnStop
OnStop () This method is called when activity is no longer visible to the user because the other activity is resumed and overwrites the activity. OnStop is called when a new activity starts and is placed in front of the activity, or the activity is destroyed to invoke OnStop Yes If the activity reloads and interacts with the user, the Onrestart method is called. If activity is destroyed, the OnDestroy method is called
OnDestroy () This method is called when activity is destroyed. Activity is destroyed in two cases, the user calls the activity of the finish method to end the activity, one is the system to save space to destroy the activity. You can call the Isfinishing method to distinguish which case Yes Nothing

Killable This column in the table is worth noting:

    1. For methods that are marked as being killable, when activity executes these methods, the process that holds the activity "at any time" can be killed by the system and no longer executes any line of code in the activity. Because of this, you should save the data in the OnPause method (for example, the user's edits). In addition, when the activity is run to the background state, the Onsaveinstancestate (bundle) method can be called to save the activity's dynamic data to a bundle object, and if the activity needs to be re-create, Bundle data can be obtained from the OnCreate.
      Note: Saving data before Android3.0 should be done in OnPause because Onsaveinstancestate is not part of the activity's life cycle and is not called during process lifecycle correlation. Changes have taken place from Android3.0 onwards. The app can be killable only after the OnStop method returns. This also causes the Onsaveinsatancestate (Bundle) to be called after the activity has been killed before the OnPause runs, and allows the app to wait until the OnStop method is run.

    2. For those methods that are not marked as being killable, the system will not kill the activity process until the method starts calling until the method returns. Thus, an activity is in a state that can be killed before calling Onresume after calling OnPause.

Three, Configuration

If the configuration of a device changes resources.configuration, the interface displayed to the user should also be updated to match the changes in the Landscape (portrait and screen). Because activity is the primary mechanism for interacting with users, it contains functions to handle changes in device configuration.
Unless you have other designations, when the configuration of your device changes (for example, screen orientation, language, input devices, and so on) you will be destroyed your current activity and experience the normal life cycle of your activity onpause–> Onstop–>ondestroy. If the activity has already been loaded into the foreground in the foreground or visible to the user, once the activity instance invokes the OnDestroy method, it will create a new instance of the activity, The activity instance can get to the previous state savedinstancestate saved through Onsaveinstancestate.
Any resource in the app, including layout files, will change based on changes in the configuration values. Thus, the safest way to handle configuration changes is to retrieve all resource files, including layouts,drawable,strings. Because the activity must know how to save their state and recreate them according to the saved state, the quickest way is to provide a new configuration to restart an activity.
In some cases, you may want to change the configuration without restarting the activity, which requires the use of the properties in the config file for Android. R.attr#configchanges android:configchanges to finish.

<!-- 当屏幕方向或者键盘方向发生改变时不去调用activity的oncreate-->android:configChanges="keyboardHidden|orientation"

When this property is configured, it means that you can monitor it and call the Onconfigurationchanged method instead of restarting the activity when the specified configuration changes.

Four, startingactivities

Open an activity and get the results
The Android.app.activity#startactivity method is used to open an activity and the activity is placed on top of the stack after it is opened. You need to use intent to indicate the activity you want to open when calling the StartActivity method.
Sometimes you might want to get a return result at the end of the activity. For example, you might open an activity that lets a user select a contact from a contact list, and when the activity ends and returns the selected result, you can use Android.app.activity#startactivityforresult ( Intent, int) opens the activity and results can be obtained in the activity's Onactivityresult method
Call the Setresult (int) method in an existing activity to return the result to its parent activity. A result code must be provided when the result is returned, either result_canceled, RESULT_OK, or another custom designator. Alternatively, you can choose to return a intent with additional data back. With the result code, all information can be obtained from the parent's onactivityresult. If a child activity crashes, the parent activity receives a result code that is result_canceled

  Public  class myactivity extends Activity {...Static Final intPick_contact_request =0; Public Boolean OnKeyDown(intKeyCode, KeyEvent event) {if(keycode = = Keyevent.keycode_dpad_center) {//When the User center presses, let them pick a contact.Startactivityforresult (NewIntent (Intent.action_pick,NewUri ("Content://contacts")), pick_contact_request);return true; }return false; }protected void Onactivityresult(intRequestcode,intResultCode, Intent data) {if(Requestcode = = pick_contact_request) {if(ResultCode = = RESULT_OK) {//A contact is picked. Here we'll just display it                  //to the user.StartActivity (NewIntent (Intent.action_view, data)); }          }      }  }
Five, Savingpersistentstate

To save a permanent state:
Activity usually holds two persistent states.

    • Shared Documents: Data (data saved in a database with content provider)
    • internal state: For example, user Preferences
      for the first class of shared data, activity should use "Edit in place" Edit the in-place user model. That is, the user can save immediately after editing, no additional steps are required. The following two rules must be followed when using this model
      1. When creating a new document, immediately create the database entry or file that he depends on. For example, if the user chooses to write a new email, the new entry associated with the email must also be created to ensure that if the user goes to any other activity the email will not disappear in the draft.
      2. When activity calls the OnPause method, he should commit the user's modifications to the data. This operation ensures that the user's modifications can be known by other activity that will be running. You may also want to proactively commit modified data at critical moments in the activity lifecycle: for example, before a new activity is opened, when the user switches input fields, and so on, before the activity is finish,
        This model is designed to prevent data loss when the user switches between activity and allows the system to safely kill the activity at any time after the activity is paused (because other places require system resources, The activity was killed). This means that the user pressing the "back" key does not mean "cancel"-it means saving his current content and leaving. Canceling edits in one activity must be provided through other mechanisms, such as an explicit "revert" or "undo" option.

The activity also provides an API to manage the internal state associated with the activity. For example, you can use it to record a user's preferences and to initialize a user's calendar, or to display a default home page for the user when using a browser.
The persistent state of activity is managed through the Getpreferences method, allowing retrieval or modification of a set of Name/value key-value pairs associated with the activity. In order for preferences to be shared between multiple components of the application (activities,receivers,services,providers), you can use the existing methods
Context#getsharedpreferences context.getsharedpreferences () to retrieve the preferences object corresponding to a particular name. (Cannot share data through preferences across processes-only through ContentProvider)
。 Here is a snippet from the calendar

 Public  class calendaractivity extends Activity {...Static Final intDay_view_mode =0;Static Final intWeek_view_mode =1;PrivateSharedpreferences mprefs;Private intMcurviewmode;protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);          Sharedpreferences mprefs = Getsharedpreferences (); Mcurviewmode = Mprefs.getint ("View_mode", Day_view_mode); }protected void OnPause() {Super. OnPause ();          Sharedpreferences.editor ed = Mprefs.edit (); Ed.putint ("View_mode", Mcurviewmode);      Ed.commit (); }  }
VI, Permissions

When you register activity in Androidmanifest, you can write a permission to the activity so that other apps need to have that permission when they open the activity.
When you open an activity, you can set the flag bit intent.flag_grant_read_uri_permission or intent.flag_grant_write_uri_permission on the Intent.
This grants activity access to specific URIs in intent. Access rights are kept to the end of activity (he will remain until the host process is killed and other temporary corruption). Android2.0, if the activity has been created and a new intent is sent to onnewintent (intent), any newly granted URI permissions will be added to the existing URI.

Seven, Processlifecycle

The

Android system tries to keep the app process as long as possible, but when memory is low, it eventually needs to kill the old process. As described in the activity lifecycle activitylifecycle, it is up to you to decide which process should be removed from the user interaction state. In general, depending on the state of the activity running in the process, you can see that there are four states of the process, sorted in order of importance. The system first kills the least important process before it is reordered to kill important processes.

    1. Foreground activity Reception activity: (activity at the top of the screen, interacting with the user) is the most important. If the memory consumed exceeds the user's available memory, the process is killed at the end. In general, the device has reached a memory paging state in this respect, so it is necessary to kill some processes in order to ensure user input fluency
    2. It is also important that the visible activityactivity (visible to the user but not in front of the user, such as a pop-up dialog above the activity), will only kill the process if the system requires that the foreground activity be kept running.
    3. Background activity (background process, activity to the user is not visible, and has been paused activity) is no longer a critical activity, so the system can be very safe to kill its process to reclaim memory run foreground Processes and visible processes. If its process needs to be killed, when the user switches back to the activity (again to the screen), the OnCreate method is called and the previous onsaveinstancestate saved data is removed from the savedinstancestate. To ensure that it gets the state when the user finally leaves when it re-opens
    4. Empty process is a process that does not have any activity or other application components. When memory is low, it is quickly killed. For this reason, any background operation outside of your activity must be performed in the context of the service and broadcastreceiver to ensure that your process is kept running.
      Sometimes an activity might need to do a long-running operation unrelated to the activity lifecycle. For example, the camera app allows you to download images from the Web. The download takes a long time and the app allows the user to leave the camera app when the download operation is performed. To achieve this, your activity should open a service to handle the download. This action allows the system to prioritize your process (considering that it is more important than other invisible applications), regardless of the state of the original activity

Android four components fully resolved (i)---Activity

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.