Activity:
In Android programs, Activity typically represents a screen on a mobile phone. If you compare your phone to a browser, then acitivity is the equivalent of a Web page. In the activity, you can add buttons, Check box and other controls. You can listen to the control and handle the user's events to respond.
Typically an Android app is made up of multiple activity. The multiple activity can jump to each other, for example, when a button is pressed, it may jump to other activity. and the page jump slightly somewhat different is that the Activity between the jump may return a value. When a new screen is opened, the previous screen is placed in a paused state and pressed into the history stack. The user can return to a previously opened screen through a fallback operation. We can selectively remove some screens that are not necessarily retained, because Android saves each app's start to the current screen in the stack. Activity is maintained by the Android system, it also has its own life cycle, that is, one of its generation, operation, destruction of a cycle, for activity, the key is its life cycle of the grasp, followed by state preservation and recovery (onsaveinstancestate Onrestoreinstancestate), as well as jumps and data transfers between the activity (intent).
Activity several processes in the life cycle
1. Start activity: The system calls the OnCreate method first, then calls the OnStart method, and finally calls Onresume,activity into the running state.
2. Current activity is overwritten or locked by other activity: the system invokes the OnPause method, pausing the execution of the current activity.
3. The current activity is returned to the foreground or unlock screen by the overwritten state: The system calls the Onresume method and enters the running state again.
4. The current activity goes to the new activity interface or press the home key to return to the main screen, itself back to the background: the system will first call the OnPause method, and then call the OnStop method, into a stagnant state.
5. The user backs back to this activity: the system calls the Onrestart method first, then calls the OnStart method, and finally calls the Onresume method, again into the running state.
6. Current activity is in a covered state or the background is not visible, that is, the 2nd and 4th steps, the system is out of memory, kill the current activity, and then the user returned to the current activity: Call OnCreate method Again, OnStart method, Onresume method To enter a running state.
7. The user exits the current activity: The system calls the OnPause method first, then calls the OnStop method, and finally calls the Ondestory method to end the current activity.
How do I create an activity in Android?
Create activity class and related view file layout (view), the activity class created by the user needs to inherit from Android.app.Activity class
Second, configuration Androidmanifest.xml file
Iii. overloaded OnCreate, binding activity and layout (View)
Iv. Add the necessary components to the view, which can be added in the XML file or added dynamically in the program.
V. Implement the initial business logic in OnCreate (), such as adding an event to a button
Each activity is in a certain state, and for the developer it is impossible to control its application in one state, which is done by the system. However, when the state of an activity changes, the developer can obtain the relevant notification information by calling ONXX (). When implementing the Activity class, these methods can be called by overwriting (override) when you need to process them.
1, OnCreate: When the activity first starts, the method is triggered, you can complete the initialization of the activity at this time.
The OnCreate method has a parameter that can be empty (null), or it can be a state information that was previously saved by calling the Onsaveinstancestate () method.
2. OnStart: This method is called when it is created or returned to the foreground from the background.
3. Onresume: When an activity interacts with the user, the method is triggered.
4. OnPause: is called when the screen is overwritten or locked
5, OnStop: When an activity no longer needs to be displayed to the user, the method is triggered. If the memory is tight, the system will end the activity directly without triggering the OnStop method. So saving state information should be done at onpause time, not onstop. Activities that are not running in the foreground will be stopped or the Linux management process can end these activities at any time in order to reserve enough storage space for the new activity. Therefore, it is important for developers to always keep this principle in mind when designing applications. In some cases, the OnPause method may be the last method of activity triggering, so developers need to save the information at this time.
6. Onrestart: Called when an activity in the stopped state is returned to the foreground from the background.
7, OnDestroy: When the activity is destroyed, the method is triggered. As with the OnStop method, if the memory is tight, the system will end the activity directly without triggering the method.
Onsaveinstancestate: This method is called by the system, allowing the activity to save its previous state, such as where the cursor is located in a string of strings. Typically, developers do not need to override this method, and in the default implementation, all state information for the user interface components involved in the AutoSave activity has been provided.
The onwindowfocuschanged, Onsaveinstancestate, and Onrestoreinstancestate methods are also added:
1.onWindowFocusChanged: Called when the activity window Gets or loses focus, such as when it was first presented to the user at the time of creation, and the current activity is overwritten by other activity The current activity goes to another activity or presses the home key back to the main screen, and the user exits the current activity. In these cases, onwindowfocuschanged is called, and when the activity is created it is called after Onresume, when the activity is overwritten or retired or the current activity exits, It is called after the OnPause
2.onSaveInstanceState: (1) After the activity is covered or back to the background, the system resources are not enough to kill, this method will be called, (2) when the user changes the screen orientation, this method will be called; (3) This method is called when the current activity jumps to another activity or presses the home key to return to the main screen. In the first case, we cannot guarantee when the system will be dispatched according to the degree of resource stress; the second is the screen flipping direction, the system first destroys the current activity, and then rebuilds a new one, we can save some temporary data when we call this method. In the third case, the system calls this method to save the state of each view component in the current window. The order in which the onsaveinstancestate is called precedes OnPause.
3.onRestoreInstanceState: (1) After the activity is covered or back to the background, the system resources are not enough to kill it, and then the user returned to the activity, this method will be called, (2) in the process of the user changing the screen direction, the reconstruction, This method is called. We can override this method so that some temporary data can be recovered. The order in which the onrestoreinstancestate is called is after OnStart.
Activity Stack
The developer is unable to control the state of activity, and what logic does the activity state work on?
The state of each activity is determined by its position in the activity stack, which is a last-in-first-out LIFO, which contains all the queues that are running activity.
Activity four different modes of loading
Standard: Normal mode, a call to the StartActivity () method produces a new instance.
Singletop: Checks if an instance exists at the top of the activity stack, does not produce a new instance if it exists, and vice versa invokes the activity's newinstance () method to produce a new instance.
Singletask: this instance is generated in a new task, and each subsequent call will use this instance to avoid creating a new instance.
SingleInstance: This is basically the same as Singletask, just a little bit different, that is, in this mode the activity instance is in the task, can only have this activity instance, and cannot have other instances.
These boot modes can be set in Android manifest file Androidmanifest.xml, via the Launchmode property in <activity>, such as:
Androidmanifest.xml
<activity android:name= "Mainactivity"
Android:launchmode= "Singletop" >
<intent-filter>
<category android:name= "Android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
Java Code
Intent Intent = new Intent (srcactivity.this, Targetactivity.class);
Intent.addflags (Intent.flag_activity_reorder_to_front);
Refer to Flag of intent.addflags ()
StartActivity (Intent);
Service Service :
A service is an application component that runs in the background without a user interface to perform time-consuming operations. Other application components can start the service, and when the user switches to another scenario, the service will continue to run in the background. In addition, a component can be bound to a service interaction with it (IPC mechanism), for example, a service may handle network operations, play music, manipulate file I/O, or interact with content providers (provider), all of which are performed in the background.
Service has two states, "initiated" (STARTD) and "bind" (Bound)
Services that start with StartService () are in the "Started" state, and once started, the service runs in the background, even if the application component that started it has been destroyed. A service that typically started a state performs a single task and does not return any results to the initiator. For example, when a file is downloaded or uploaded, the service should stop itself when the operation is complete.
There is also a "bind" state of service, which is initiated by calling Bindservice (), a bound service that provides an interface that allows the component to interact with the service, can send requests, get return results, and can interact (IPC) through the Kua process communication. A bound service can be run only after the application component is bound, and multiple components may bind to a service, and when the Unbind () method is called, the service is destroyed.
Note: Service is the same as activity in the main thread of the current process, so some actions that block the UI, such as time-consuming operations, cannot be placed in the service, such as opening a thread to handle time-consuming operations such as network requests. If some CPU-intensive and time-consuming operations are performed in the service, a ANR warning may be raised, and the application pops up a dialog box that is forced to close or wait. So, the understanding of the service is the same as the activity, but is invisible, in the background to run a component, which is why and activity is said to be the basic components of Android.
Service life cycle:
As you can see from this diagram, the two ways to start the service and their declaration cycle, the BIND service differs in that the corresponding service is killed when the bound component is destroyed. The service's declaration cycle is a lot simpler than the activity, as long as you understand the similarities and differences between the two startup service modes.
Only OnStart can be called multiple times (through multiple StartService calls) during each turn-off of the service, and the other oncreate,onbind,onunbind,ondestory can only be called once in a life cycle.
Service, there are two additional modes depending on the return value of the Onstartcommand:
The start_sticky is used to display the start and stop service.
The Start_not_sticky or start_redeliver_intent is used to run a pattern when the command needs to be processed.
The service cannot run itself and needs to start the service by calling the Context.startservice () or Context.bindservice () method.
The service is enabled with the StartService () method, the caller is not connected to the service, and the service is still running even if the caller exits.
Using the Bindservice () method to enable the service, the caller binds to the service, and the caller exits and the service terminates.
1) startservice Start-up service
private void Startcustomservice () {Intent intent=new Intent (this,localservice.class); StartService (Intent); }
2) 2) Start the service with the Bindservice method
LocalService Localservice=null;
private void Binderservice () {
Intent intent=new Intent (this,localservice.class);
Bindservice (Intent, New Serviceconnection () {
@Override
public void onserviceconnected (ComponentName componentname, IBinder binder) {
Call the Bindservice method to start the service, if the service needs to interact with the activity,
The Onbind method returns the IBinder and returns the current local service
Localservice= ((Localservice.localbinder) binder). GetService ();
Here you can either prompt the user, or invoke some method of the service
}
@Override
public void onservicedisconnected (ComponentName componentname) {
Localservice=null;
Here you can prompt the user
}, Context.bind_auto_create);
}
Broadcast Receiver ( broadcast receiver )
Broadcast receiver is used to receive and process broadcast notifications (broadcast announcements). Broadcastreceive has 1, system broadcast events, such as: action_boot_completed (triggered when the system starts to complete), action_time_changed (triggered when the system time changes), Action_battery_ Low (triggers when the battery is lower), and so on. 2, user-defined broadcast events. Broadcast receiver can notify users in a variety of ways: Start activity, use Notificationmanager, turn on background lights, vibrate devices, play sound, etc., most typically in the status bar display an icon, This allows the user to click on it to open the notification content.
Usually one of our applications or the system itself in certain events (low battery, call to SMS) to temporarily broadcast a intent out, we can use to register a broadcast receiver to hear these intent and get the data in intent.
Receiving broadcast requires registering a broadcast receiver and registering a intent filter to determine which intent the Broadcase receiver is listening to.
Our own program is actively broadcasting intent
Final String broadcast = "Com.forrest.action.mybroadcast";
Intent Intent = new Intent (broadcast); corresponding setaction ()
Intent.putextra ("Data_title", " to SMS " );
Intent.putextra ("Data_text", " beauty Hello, evening can be free ");
Sendbroadcast (Intent);
Receive broadcasts
Receiving broadcast requires registering a broadcast receiver and registering a intent filter to determine which intent the Broadcase receiver is listening to.
(1) Create broadcast Receiver
A broadcast receiver has only one simple callback function: OnReceive (Context curcontext, Intent broadcastmsg), when a broadcast message is monitored by receiver, Android calls its OnReceive () method and passes the intent object containing the message to it. OnReceive the code in the execution time does not exceed 5s, otherwise Android will eject timeout dialog. Is it time to open another thread to handle the time-consuming operation?
Receiver is active only when the OnReceive method executes, as long as onreceive returns, receiver is no longer active. The receiver process is protected by an activated broadcast receiver without being terminated by the system, and once OnReceive returns, the receiver process broadcast receiver is protected and becomes an empty process. An empty process can be terminated at any time. This poses a problem: when responding to the processing of a broadcast message is time-consuming, it should be done in a separate thread to ensure that the other user interaction components of the mainline thread can continue to run, and once the OnReceive () evokes a thread, it returns immediately. At this point the receiver process is put to the end of the situation. The solution to this problem is to start a service in OnReceive () to let the service do this, and the system will assume that there is still activity going on in the process.
(2) Registration/deregistration of broadcast Receiver
1) Register in Androidmanifest.xml, register a broadcast address for myreceiver
<receiver android:name= ". Myreceiver" >
<intent-filter>
<!--and action in intent
<action android:name= "Com.forrest.action.mybroadcast"/>
</intent-filter>
As long as it's com.forrest.action.mybroadcast this address, you can get it.
2) registering in the code
Intentfilter filter = new Intentfilter ("Com.forrest.action.mybroadcast");
and the action corresponding to the intent in the broadcast
Mybroadcastreceiver br = new Mybroadcastreceiver ();
Registerreceiver (New Mybroadcastreceiver (), filter);
3) write-off Unregisterreceiver (BR);
http://blog.csdn.net/liuhe688/article/details/6955668, this post has a detailed introduction
ContentProvider ( content provider )
For sharing data externally, sharing data from the app to other apps via ContentProvider, and other apps can manipulate data in the specified app through ContentProvider. ContentProvider is divided into the system and the custom, the system is also. such as contact person, picture and other data.
Data manipulation in Android includes: file, Sqlite3, Preferences, Contectresolver, and contentprovider the first three data manipulation methods are only for the data in this application, The program cannot manipulate data from other applications in these three ways
The content provider inherits from the ContentProvider base class. An application implements ContentProvider to provide content to other applications, and an application uses Contentresolver to manipulate other application data,
1, ContentProvider
Android offers some of the main data types of contentprovider, such as audio, video, images, and personal contacts. Some Android-provided ContentProvider can be found under the Android.provider package. By obtaining these contentprovider, you can query the data they contain, as long as the appropriate read permissions have been obtained.
2, Contentresolver
When external applications need to add, delete, modify, and query the data in ContentProvider, you can use the Contentresolver class to get the Contentresolver object, You can use the Getcontentresolver () method provided by the context.
Intent:
The activity communicates through intent. In the description structure of intent, there are two most important parts: the data corresponding to the action and the action.
Typical types of actions are: MAIN (activity Portal), VIEW, PICK, EDIT, and so on. The data corresponding to the action is represented in the form of a URI. For example, to see a person's contact, you need to create a intent with the action type view and a URI that represents the person.
A class that has a relationship with it is called Intentfilter. As opposed to intent is a valid request to do something, a intentfilter is used to describe which intent an activity (or intentreceiver) can manipulate. An activity if you want to display a person's contact information, you need to declare a intentfilter, this intentfilter to know how to handle the view action and the URI that represents a person. Intentfilter needs to be defined in Androidmanifest.xml.