Android Inventory file details (iii)----The root node of the application <application>

Source: Internet
Author: User
Tags function prototype

The <application> node is a node that must be held in the Androidmanifest.xml file, which is included under the <manifest> node. With the related properties of the <application> node, we can declare the relevant features of the Android application. This node contains nodes for all application components, including activity, services, broadcast receivers, and content providers, and contains properties that may affect all components. Some of these properties are set to the same properties of the application component as the default values, such as icon,label,permission,process,taskaffinity and allowtaskreparenting, Some of the other values are set as the whole of the application and cannot be overridden by the properties of the application component, such as Debuggable,enabled,description and Allowclearuserdata.

1.<application> node Configuration

In general, when building an Android application, the default Androidmanifest.xml file already contains some default <application> nodes that contain the basic properties of the application. Now let's take a look at the complete set of <application> node information, with the following code:

<application android:allowtaskreparenting=["true" | " False "]

Android:backupagent= "string"

Android:debuggable=["true" | " False "];

Android:description= "String Resource"

Android:enabled=["true" | " False "]

Android:hascode=["true" | " False "]

Android:hardwareaccelerated=["true" | " False "]

android:icon= "Drawable Reource"

Android:killafterrestore=["true" | " False "]

Android:label= "String Resource"

android:logo= "Drawable Resource"

Android:managespaceactivity= "string"

Android:name= "string"

Android:permission= "string"

Android:persistent=["true" | " False "]

Android:process= "string"

Android:restoreanyversion=["true" | " False "]

Android:taskaffinity= "string"

Android:theme= "resource or Theme" >

</application>

2. How to implement the Application class

The first thing to introduce is the Android:name attribute, which refers to the subclass of the application class, when the application process is started, the class specified by the Android:name property will be in all application components (activity, service, broadcast receiver, The content provider) is instantiated before being instantiated.

In general, the application does not need to specify this property, and Android instantiates the Applicaiton class under the Android framework.

However, in some special cases, such as the desire to complete an initialization before the application component is started, or to do some special processing when the system is low in memory, consider implementing a subclass of your own application class.

In the system application provided by the Android system, one has implemented its own application instance, and this application is launcher. We can imitate it to achieve a application class, the specific steps are as follows.

① creates a project called Applicationtest and adds a line of code to the OnCreate () method in the default generated mainactivity to output a log. This will allow you to see the application creation time, with the following code:

public class Mainactivity extends Activity {    private static final String tag= "mainactivity";    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        LOG.E (TAG, "mainactivity is created");}    }

② implementation of its own MyApplication class, the code is as follows:

public class MyApplication extends application {    private static final String tag= "MyApplication";    @Override public    void OnCreate () {        super.oncreate ();        LOG.E (TAG, "MyApplication is created");}    }

③ adding MyApplication to the Androidmanifest.xml <application> inside android:name of the manifest file

As you can see, Android first created the MyApplication and finally created the mainactivity.

Functions provided by 3.Application and their usage

The Android.app.Application class provides a number of methods similar to OnCreate (), which are recalled by the Android framework in different scenarios. At the same time, the application class provides a number of monitoring functions to monitor the life cycle of components in this application. As shown in the following table:

Method name return value
Annotations
Onconfigurationchanged (Configuration newconfig) void If the device configuration (including language, orientation, network, etc.) changes when the component is running, the system calls this method to notify the application
OnCreate () void This method is called when the application is starting up, and before any other application objects are created. Because the time spent on this feature directly affects the speed at which the first activity service or receiver is started in a process, it executes as quickly as possible (for example, with a slow initialization state). If you override this method, you need to make sure that you call super.oncreated ()
It is important to note that in a real application, if some components in your application specify a process attribute (the processes) and this process does not exist, then the application OnCreate () callback is called, in other words, this method may be called multiple times
Onlowmemory () void The system calls this method to notify the application when the entire system is running low on memory and wants the application to reduce memory usage. But when the exact point of the call to this method is undefined, it usually occurs near the time that all background processes have been terminated.
The application can perform this method to free any buffers or unnecessary resources that it owns. The system runs a garbage collection operation after it returns from this method.
Onterminate () void This method is used in a simulation process environment and is not invoked on the production Android device, and can be removed by simply terminating the process on the production Android device. Do not execute any user code (including this callback) when you remove work
Ontrimmemory () void Called when the memory is reclaimed. For example, when it goes into the background and there is not enough memory to keep many background processes running.
Monitoring Callback Interface
Registercomponentcallbacks
Unregistercomponentcallbacks
void

void
Register an Componentcallbacks interface in the application. The application is notified through the various methods of this interface before the activity life cycle has changed. Using this interface, we can do the necessary processing before the activity life cycle changes
It is important to note that the Componentcallbacks object must be removed at the appropriate time in the future, using Unregistercomponentcallbacks (componentcallbacks). It was previously registered with Registercomponentcallbacks (componentcallbacks).

Next, we illustrate how to use these methods and interfaces with some examples

① using the Onconfigurationchanged () method to monitor system configuration updates

The function prototype of the onconfigurationchanged () method is as follows:

public void onconfigurationchanged (configuration newconfig) {} where the Newconfig parameter represents the new device configuration

The Onconfigurationchanged () method is a callback interface that is called by the Android system when the device configuration changes. At the same time, the Android system passes the parameters (Newconfig) to the application and the application handles the change. Note that unlike activity, other components are never restarted when a configuration changes, and they are weak to handle the results of the changes themselves. The "configuration" described here is shown in the following table:

Configuration Items Annotations
Fontscale Represents the font scale for the current system, which is scaled based on pixel density.
Note that in the system firmware compiled with user mode, the interface that modifies this configuration is not included and can only be changed programmatically.
Data type: floating-point type
Hardkeyboardhidden Indicates whether the hard keyboard is hidden, this configuration item has 3 values, as shown below.
0.hardkeyboardhidden_undefined (Android unrecognized keyboard state)
1.hardkeyboardhidden_no (hard keyboard available)
2.hardkeyboardhidden_yes (hard keyboard is hidden)
Data type: Integral type
Keyboard Indicates which kind of keyboard is added to the device, and this configuration entry has the following 4 values
0.keyboard_undefined (Android unrecognized keyboard)
1.keyboard_nokeys (no key keypad)
2.keyboard_qwerty (typewriter keyboard)
3.keyboard_12key (12-key keyboard)
Data type: Integral type
Keyboardhidden Indicates whether a keyboard is currently available. If you have a hard keyboard on your Android device that has a hard keyboard, and you still have a soft keyboard, you think the keyboard is available. This field has the following 3 values.
0.keyboardhidden_undefined (Android unrecognized keyboard state)
1.keyboardhidden_no (still visible with soft keyboard)
2.keyboardhidden_yes (all soft keyboards are hidden).
Data type: Integral type
Locale Defines the language environment for the device. It contains country and language information that is contained in an object of type Java.util.Locale
Mcc IMSI the mobile country code, if it is 0, indicates undefined.
Note: IMSI refers to the International Mobile Subscriber ID, which is stored in our SIM card with a total length of not more than 15 bits.
Data type: Integral type
Mnc IMSI mobile network number, if 0 indicates undefined
Data type: Integral type
Navigation Indicates the navigation mode available for the current device, which has the following 5 values.
0.navigation_undefined (undefined navigation mode)
1.navigation_nonav (no navigation)
2.navigation_dpad (Panel navigation mode)
3.navigation_trackball (trackball Navigation)
4.navigation_wheel (scroll mode navigation)
Data type: Integral type
Navigationhidden is used to indicate whether the navigation is available and has the following values.
0.navigationhidden_undefined
1.navigationhidden_no
2.navigationhidden_yes
Data type: Integral type
Orientation A flag indicating the orientation of the screen with the following 4 values.
0.orientation_undefined (undefined method)
1.orientation_portrait (vertical screen orientation, screen width less than height)
2.orientation_landscape (horizontal screen direction, screen width greater than height)
3.orientation_square (square screen, think screen width equals height)
Note: When you calculate a new configuration in Window Management Services (Windowmanagerservice), the default configuration for orientation is Orientation_square
Data type: Integral type
Screenheightdp Height of the available portion of the screen
Screenlayout Indicates the overall properties of the screen, which consists of two sections.
⒈screenayout_size_mask: Flag Screen Size properties (such as large screen, small screen, etc.), it has the following 5 values.
screenayout_size_undefined: Undefined (value: 0)
Screenayout_size_small: Small screen (value: 1, screen resolution is at least 320*426).
Screenayout_size_normal: Normal screen (value: 2, screen resolution is at least 320*470)
Screenayout_size_large: Large screen (value: 3, screen resolution of at least 480*640)
Screenayout_size_xlarge: Enlarge screen (value: 4, screen resolution is at least 720*960)
⒉screenayout_long_mask: Indicates whether the screen is higher or wider than usual, and it has the following 3 values.
screenayout_long_undefined: Undefined (hex value is 0)
Screenayout_long_yes: Yes (hexadecimal value is 20)
Screenayout_long_no: No (hexadecimal value is 10)
Screenwidthdp Width of the available portion of the screen
Smallestscreenwidthdp In normal operation, the application will see the smallest screen size. This is the minimum value for SCREENWIDTHDP and SCREENHEIGHTDP in vertical and horizontal screens.
Touchscreen The type of touch screen on the device, which supports the following values.
0.touchscreen_undefined (undefined mode)
1.touchscreen_notouch (no touch screen mode)
2.touchscreen_stylus (Stylus mode)
3.touchscreen_finger (Finger touch screen mode)
Uimode The bitmask of the UI pattern, which currently has two fields.
⒈ui_mode_type_mask: Defines the entire UI mode of the device, which supports the following values.
Ui_mode_type_undefined: Unknown mode
Ui_mode_type_normal: Normal mode
Ui_mode_type_desk: with base mode '
Ui_mode_type_car: Car mode
⒉ui_mode_night_mask: Defines whether the screen is in a special mode. It supports the following values.
ui_mode_night_undefined: no pattern defined
Ui_mode_night_no: Non-night mode
Ui_mode_night_yes: Night Mode

Below we show an example of how the system notifies the application via the Onconfigurationchanged callback interface when the device configuration changes.

㈠ adds a subclass of application named Configapplication to the previous application, and implements the OnCreate () method and the Onconfigurationchanged () method. In the OnCreate () method, we get the configuration information that the application has at the beginning of its creation. In the Onconfigurationchanged () method, you can add some code to use the log to reflect configuration updates in real time. The relevant code is as follows:

public class Configapplication extends application {    private static final String tag= "configapplication";    Private Configuration mconfiguration;    @Override public    void OnCreate () {        super.oncreate ();        This.mconfiguration=getresources (). GetConfiguration ();//Get configuration information        log.e (TAG, "oncreate::infomation:orientation = "+this.mconfiguration.orientation);    }    @Override public    void onconfigurationchanged (Configuration newconfig) {        super.onconfigurationchanged ( Newconfig);        Print updated configuration information        log.e (TAG, "onconfigurationchanged:infomation:orientation=" +newconfig.orientation);}    }

㈡ the configapplication configuration to the Androidmanifest.xml file as described earlier.

㈢ The device runs the application, you can see the following log information.

For the log, the description is as follows:

The first line of the log information is the orientation configuration in the initial state, through which we know that the initial direction value is 1. And according to the previous table, it is now the vertical screen direction.

The fifth line of log information is to switch the horizontal screen, the Android system callback our implementation of the Onconfigurationchanged () method, then the system configuration has changed, so the log here to print the current screen direction is 2, also on the horizontal screen.

Recommendation: Because of the invocation of some callback interfaces implemented in the base class Onconfigurationchanged () method, if we rewrite this method, then in order to maintain the behavior of the original application class, It is recommended to call Super.onconfigurationchanged (Newconfig) at the overridden method entry.

② using OnCreate () to complete application initialization

The prototype of the OnCreate () method is:

public void OnCreate () {}

As shown in the previous table, the OnCreate () method is a callback interface. The Android system calls this interface when the application is launched, before any application components (Activity, service, broadcast receiver, content provider) are created.

It is important to note that the execution efficiency of this method directly affects the performance of the initiating activity, service, broadcast receiver, or content provider, so the method should be completed as soon as possible.

Finally, if you implement this callback interface, please do not forget to call Super.oncreate (), or the application will error.

We have implemented the subclass------Configuration of the Appplication class, and have implemented our own OnCreate () method. Here's a little experiment to get a better idea of the knowledge.

Now, add a wait of about 20 seconds in the OnCreate () method of the source code to simulate a situation in which the OnCreate () method has done too much work to cause the method to fail for a long time, and the modified code is as follows:

public class Configapplication extends application {    private static final String tag= "configapplication";    Private Configuration mconfiguration;    @Override public    void OnCreate () {        super.oncreate ();        This.mconfiguration=getresources (). GetConfiguration ();//Get configuration information        log.e (TAG, "oncreate::infomation:orientation = "+this.mconfiguration.orientation");        Systemclock.sleep (20000);//Sleep 20 seconds    }    @Override public    void Onconfigurationchanged (Configuration Newconfig) {        super.onconfigurationchanged (newconfig);        Print updated configuration information        log.e (TAG, "onconfigurationchanged:infomation:orientation=" +newconfig.orientation);}    }

Run the program at this time, the program will crash, of course, on the real device can wait, and some do not cause crashes, such as the test on Xiaomi 50 seconds, the program does not crash, but wait until the program is normal. When this creates a bad user experience. So in the future development process, to fully consider these error-prone situations.

③ using the Onlowmemory () callback method to monitor low memory

The prototype of this method is:

public void Onlowmemory () {}

This method is called when the entire system is running in low memory.

A good application implements this method to free any cache or other unwanted resources. After the system returns from this method, a garbage collection operation is performed.

④ use Registeractivitylifecyclecallbacks () to register interfaces that can monitor the activity lifecycle

The prototype of the Registeractivitylifecyclecallbacks () method is:

public void Registeractivitylifecyclecallbacks (Application.activitylifecyclecallbacks callback) {}

In this method, the parameter callbacks represents the interface of the activity life cycle.

From Android4.0 onwards, the Android SDK provides a complete set of interfaces for the application to monitor the lifecycle of activity associated with this application (create, start, pause, etc.). Its name is called Activitylifecyclecallbacks. As long as the interface is registered through the Registeractivitylifecyclecallbacks () method in the application, It provides the relevant activity lifecycle information in the application through Activitylifecyclecallbacks. The following table lists these interfaces and their purpose.

Method prototypes Parameter description Use
abstract void onactivitycreated (Activity activity,bundle savedinstancestate) Activity: An activity instance created
Savedinstancestate: The information that was taken when the activity was created (a bundle instance)
Called before the application creates an activity to inform the interface that the implementation activity will be created.
abstract void onactivitydestroyed (activity activity) Activity: Instances of activity destroyed Called before the application destroys the activity, which notifies the interface implementation that the activity will be destroyed.
abstract void onactivitypaused (activity activity) Activity: Paused Activity instance Called before the application pauses activity to inform the interface that the implementation activity is about to be paused.
abstract void onactivityresumed (activity activity) Activity: Instance of activity resumed Called before the application resumes activity, to inform the interface that the implementation of the activity is about to be resumed.
abstract void Onactivitysaveinstancestate (Activity activity,bundle outstate) Activity: An activity instance that is being persisted in the state of execution
Outstate: The activity state that needs to be saved
Indicates that the current activity is saving its own state, which is contained in Outstate.
abstract void onactivitystarted (activity activity) Activity: instance of activity started Called before the application is starting activity to inform the interface that the implementation activity is about to be started.
abstract void onactivitystopped (activity activity) Activity: A Stopped activity instance Called before the application is stopping activity to notify the interface that the implementation of the activity will be stopped.

Special reminder: From the interface definition, we can know the following information.

Ⅰ These interfaces are abstract, so when we implement the Activitylifecyclecallbacks interface, we must implement these methods, even if it is just an empty implementation.

Ⅱ The return values of these interfaces are void, which means they are used for notifications only and have no use.

In addition, we need to call the Unregisteractivitylifecyclecallbacks () method to log off the previously registered interface to avoid unnecessary waste of resources.

The following is an example of how the system notifies the application via the onconfigurationchanged () callback interface when the configuration has changed, as shown in the steps below.

The ㈠ implements its own application subclass (called alcapplication). We will register our Activity lifecycle interface when the application is created (in the OnCreate () method) and unregister this interface when the program terminates (in the Onterminate () method). When you are done with this, you will get the code that looks like this:

public class Alcapplication extends application {Private final static String tag= "Alcapplication";        Private Activitylifecyclecallbacks mactivitylifecyclecallbacks=new activitylifecyclecallbacks () {@Override        public void onactivitycreated (activity activity, Bundle savedinstancestate) {log.e (TAG, "onactivitycreated"); } @Override public void onactivitystarted (activity activity) {LOG.E (TAG, "onactivitystarted        ");        } @Override public void onactivityresumed (activity activity) {LOG.E (TAG, "onactivityresumed"); } @Override public void onactivitypaused (activity activity) {LOG.E (TAG, "onactivitypaused")        ;        } @Override public void onactivitystopped (activity activity) {LOG.E (TAG, "onactivitystopped"); } @Override public void onactivitysaveinstancestate (activity activity, Bundle outstate) {L OG.E (TAG, "OnactivitysaVeinstancestate "); } @Override public void onactivitydestroyed (activity activity) {LOG.E (TAG, "onactivitydestroyed")        ;    }    };        @Override public void OnCreate () {super.oncreate ();    Registeractivitylifecyclecallbacks (this.mactivitylifecyclecallbacks);        } @Override public void Onterminate () {super.onterminate ();    Unregisteractivitylifecyclecallbacks (this.mactivitylifecyclecallbacks); }}

㈡ configures the alcapplication to Androidmanifest.xml, and when the configuration is complete, the final result looks similar to the following:

Here we monitor activity from the launch to the launch lifecycle through the interface.

In this example, we do the logoff interface in the Onterminate () method. However, it is worth noting that the Onterminate () method is only called in the virtual machine process and is never invoked on a real Android device.

⑤ uses Registercomponentcallbacks () to register an interface that can be used for the ship activity life cycle

The prototype of this method is:

public void Registercomponentcallbacks (Componentcallbacks callback) {}

Where parameter callback is an implementation of the Componentcallbacks interface. When the activity's lifecycle changes, the application is notified through this interface. For all applications, it is the interface of the generic callback API collection. Only two methods are included in Componentcallbacks, respectively, public abstract void onconfigurationchanged (Configuration newconfig) and public abstract void Onlowmemory (). The invocation of these two methods is the same as the calling condition of the callback method with the same name in application.

Use of the Componentcallbacks () and Registercomponentcallbacks () methods with Activitylifecyclecallbacks () The use of Registeractivitylifecyclecallbacks () is the same, and here is not just an example.

Android Inventory file details (iii)----The root node of the application <application>

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.