Seven points that Android Application objects must master

http://www.2cto.com/kf/201303/193893.html

 

 1:What is Application?

Application, like Activity and Service, is a system component of           the android framework . When the android program starts, the system creates an application object to store some information about the system. Usually we don't need to specify an Application, then the system will automatically create it for us. If we need to create our own Application, it is very simple to create a class that inherits Application and register it in the application tag of the manifest (just add to the Application tag You can set the name of your own Application in the name attribute).
The android system will create an object of the Application class for each program runtime and only one, so Application can be said to be a class in the singleton mode. And the life cycle of the application object is the longest in the entire program. The life cycle is equal to the life cycle of the program. Because it is a global singleton, the objects obtained in different Activity and Service are the same object. Therefore, some operations such as data transmission, data sharing, data caching, etc. are carried out through the Application.
 
 
   2: Pass data through Application
         If there is an Activity A, jump to Activity B, and need to recommend some data, the usual method is Intent.putExtra() to let the Intent carry it, or there is a Bundle that adds information to the Bundle and let the Intent recommend the Bundle object to achieve delivery. But there is a problem with this, the data types that Intent and Bundle can carry are all basic data types. If you want to implement complex data transfer, it is more troublesome, usually you need to implement Serializable or Parcellable interface. This is actually a method of IPC data transfer in Android . If our two activities are in the same process, why bother, just pass the reference of the object that needs to be passed.
        The basic idea is this. Create a HashMap in Application, with string as index and Object as value so that our HashMap can store any type of object. In Activity A, put the object to be passed into this HashMap, and then pass the index string to Activity B through Intent or other means, and Activity B can take out the object in HashMap according to this string. As long as you turn down another type, the object transfer is realized.
 
 
  3:Application data cache
  I am generally used to establishing two HashMaps in the application, one for data transfer and one for caching some data. For example, there is an Activity that needs to obtain some data from the website. After obtaining it, we can cache the data in the Application. When the page is set to other Activity and then comes back, we can directly use the cached data. But if you need to cache some large amount of data, it is best to cache some (soft reference) SoftReference, and cache the data to the local rom or sd card. If the cache in the application does not exist, it is searched from the local cache, and if the locally cached data does not exist, it is obtained from the network.
 
 
  4: PitFalls (Chinese: easy mistakes)
      
If you use Application to save some objects that should not be saved, it is easy to cause memory leaks. If a time-consuming operation is performed in the oncreate of the Application, it will directly affect the startup time of the program. Some cleanup work cannot be done by onTerminate, because Android will try to keep your program running, so it is very likely that onTerminate will not be called.
 
 
  5:MemoryLeak
A memory leak in Java is only when an object (some) is no longer in use and should be reclaimed by gc, but there is an object holding a reference to this object that prevents this object from being reclaimed. For example, we usually create a View TextView tv = new TextView(this); the this here is usually Activity. So this TextView holds a reference to this Activity. Take a look at the picture below (copied from Google IO 2011 ppt)
Normally, when the user turns the phone, android will re-call the OnCreate() method to generate a new Activity, and the original Activity should be recycled by the GC. But if there is an object such as a View whose scope exceeds the Activity (for example, there is a static object or we put the reference of the View into the Application), then the original Activity will not be recycled by the GC, and the Activity itself holds There are many references to objects, so the whole Activity's memory is leaked.
 
      Note: The core reasons that often lead to memory leaks:
       keeping a long-lived reference to a Context. Holding a context object, so gc cannot recycle.
      details as following:
      1. The scope of a View exceeds the scope of the Activity where it is located, such as a static View or a View cached into the application, etc.
        Understanding: memory: pay attention to static data and data in the cache; pay attention to release;
   2. The scope of some Drawable associated with the View exceeds the scope of the Activity.
         3. Runnable object: For example, a new thread is enabled in an Activity to perform a task. During this period, the Activity is recycled by the system, but the Runnalbe task has not been executed and the reference of the Activity is leaked, but this Leaks generally leak for a period of time. Only after the execution of the Runnalbe thread is completed, the Activity can be recycled normally.
   
4. The object scope of the memory class exceeds the scope of the activity: for example, a memory class is defined to store data, and the object of this memory class is passed to other activities or services. Because the object of the inner class holds a reference to the current class, it also holds a reference to the Context. The solution is to write the inner class as static if the current reference is not needed, or extract the inner class into a separate class, or avoid the scope of the inner object from exceeding the scope of the Activity. Out Of Memory Error The memory size allocated by each program in android is limited, if it exceeds this number, Out Of Memory Error will be reported. The memory size allocated by android to the program is related to the mobile phone hardware. The following are some mobile phone data:
           G1:16M Droid:24 Nexus One:32M Xoom:48Ms
So try to cache some large data in the program to local files. To avoid excessive memory usage.
       Remember to remove the data stored in the HashMap of the application after the data transfer is completed to avoid memory leaks
 
 
   6: Lifecycle:
  onCreate is created when the application is created
  onTerminate is called when the application object is terminated. It is not guaranteed to be called. When the program is terminated by the kernel to release resources for other applications, then
Then it will not be reminded, and the process will be terminated directly without calling the onTerminate method of the application's object.
  onLowMemory This method is called when the background process has terminated and is still low on resources. Good applications generally release some unnecessary items in this method.
The resources needed to cope with the situation when the background program has terminated and the memory of the foreground application is not enough.
  onConfigurationChanged Trigger this method when the configuration changes
 
Remarks: Analysis of application being killed:
       In order to decide which process to kill when memory is low, Android divides the processes into an "importance hierarchy" based on the components running in those processes and their state. The importance levels are sorted according to the following rules:
 1: The front-end process can be a process that holds an Activity running at the front of the screen and interacting with the user (when the onResume method is called), or it can hold a running IntentReceiver (that is, he is executing his own onReceiveIntent) method) process. In the system, there are only a few such processes, and unless the memory is low enough for these processes to run, the system will not actively kill these processes. At this time, the device has usually reached the need for memory sorting. state, so killing these processes is to prevent the UI from becoming unresponsive.
2: A visible process is a process that holds an Activity that is visible to the user, but not displayed in the front-end (when the onPause method is called). For example, this process usually appears in a front-end Activity as a dialog box and When keeping the previous Activity visible. This kind of process is considered extremely important by the system, and is usually not killed unless it has to be killed in order to keep all front-end processes running normally.
3: The service process is a process that holds a Service, which is started by the startService() method. Although these processes cannot be seen directly by users, usually the work they do is of great concern to users (for example, playing mp3 in the background) Or download and upload files in the background), so, unless to keep all front-end processes and visual processes running normally, the system will not kill the service process.
4: A background process is a process that holds an Activity (when the onStop() method is called) that is no longer visible to the user. These processes will not directly affect the user experience. Joining these processes has completed its own life correctly. Period (see Activity for more details), the system will kill these background processes at any time when freeing memory for the first three processes. Usually there are many background processes running, so these processes are stored in an LRU list to It is guaranteed that when memory is low, the last process seen by the user will be killed last.
 5: An empty process is a process that does not hold any active application components. The only reason to keep such a process is to provide a caching mechanism to shorten the startup time of his application the next time it runs. By itself, the system kills The purpose of killing these processes is to balance the resources of the entire system between these empty processes and the underlying core cache. www.2cto.com
When a process needs to be classified, the system will select the highest level of importance among all components that are active in the process as the classification basis. See the documentation for Activity, Service, and IntentReceiver to understand how each component is used throughout the life of the process. Contributions in the lifecycle. The documentation for each class details the role they play in the lifecycle of the respective application.
 
 
 7:application 的context
        1. It describes the information of an application environment, that is, the context.
        2. This class is an abstract class, and Android provides a concrete implementation class of this abstract class (we will talk about the ContextIml class later).
        3. Through it, we can obtain the resources and classes of the application, and also include some application-level operations, such as: starting an Activity, sending a broadcast, and accepting an Intent
      information, etc. .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326356820&siteId=291194637