One post learns to develop four main components for Android and four major components for android

Source: Internet
Author: User
Tags call back

One post learns to develop four main components for Android and four major components for android

From: http://www.cnblogs.com/pepcod/archive/2013/02/11/2937403.html

This article focuses on four major components of Android development.

I. Activity details
Ii. Service Details
Iii. Explanation of Broadcast Receiver
Iv. Detailed description of Content Provider
In addition, a detailed description of an important component intent is provided.



I. Activity details
The lifecycle of Activty, that is, the lifecycle of the process in which it is located.

 


 

The startup sequence of an Activity:

OnCreate () --> onStart () --> onResume ()

When another Activity is started:
The first Activity onPause () --> The second Activity onCreate () --> onStart () --> onResume ()
--> The first Activity onStop ()

When the first Activity is returned:
The second Activity onPause () --> the first Activity onRestart () --> onStart () --> onResume ()
--> The second Activity onStop () --> onDestroy ()

Sequence of Activity destruction:
(Case 1) onPause () --> <Process Killed>
(Case 2) onPause () --> onStop () --> <Process Killed>
(Case 3) onPause () --> onStop () --> onDestroy ()

Every Activity is in a certain state. for developers, they cannot control that their applications are in a certain state, which is completed by the system.

However, when the status of an activity changes, the developer can call onXX () to obtain related notification information.

When implementing the Activity class, you can call the override methods when you need to process them.


I. onCreate: This method is triggered when the activity is started for the first time. The initialization of the activity can be completed at this time.
The onCreate method has a parameter that can be null or saved by calling the onSaveInstanceState () method. 2. onStart: the trigger of this method indicates that the activity will be displayed to the user. 3. onResume: This method is triggered when an activity interacts with the user. 4. onPause: This method is triggered when an activity that is running on the foreground is transferred to the background for running because other activities need to be run on the foreground. At this time, the activity status should be persistent, such as the database records being edited. 5. onStop: This method is triggered when an activity no longer needs to be presented to users. If the memory is insufficient, the system will directly end the activity without triggering the onStop method. Therefore, the State information should be saved in onPause instead of onStop. If the activity is not running on the foreground, it is stopped or the Linux management process ends the activity at any time to reserve enough storage space for the new activity. Therefore, developers must always keep this principle in mind when designing applications. In some cases, the onPause method may be the final method of event triggering. Therefore, developers need to save the information to be saved at this time. 6. onRestart: This method is triggered when a stopped activity needs to be displayed to the user again. 7. onDestroy: This method is triggered when the activity is destroyed. Like the onStop method, if the memory is insufficient, the system will directly end this activity without triggering this method. · OnSaveInstanceState: The system calls this method to allow the activity to save the previous state, such as the position of the cursor in a string.
Generally, developers do not need to override this method. In the default implementation, all the status information of the user interface components involved in the activity is automatically saved.

 

Activity Stack

 

As mentioned above, developers cannot control the status of the Activity. What logic does the Activity status operate? This requires you to know the Activity stack.
The status of each Activity is determined by its position in the Activity stack (a later-in-first-out LIFO that contains all queues running the Activity.
When a new Activity is started, the Activity of the current Activity moves to the top of the Activity stack.
If you use the back button to return the result, or the foreground Activity ends, the Activity will be removed from the stack and die out, the Activity of the previous Activity on the stack will be moved up and changed to the Activity state. As shown in: the priority of an application is affected by the Activity with the highest priority. When determining whether an application ends to release resources, Android memory management uses stacks to determine the priority of Activity-based applications.
Activity Status
Generally, Activity has the following four States:
Active: when an Activity is on the top of the stack, it is visible, focused, and user input acceptable. Android tries to maintain its Activity status as much as possible, killing other activities to ensure that the current Activity has enough resources to use. When another Activity is activated, it will be paused.
Pause: in many cases, your Activity is visible but has no focus. In other words, it is paused. The possible cause is that a transparent or non-full screen Activity is activated.
When paused, an Activity is regarded as an Activity, but user input is not acceptable. In special cases, Android will kill a paused Activity to provide sufficient resources for the Activity. When an Activity changes to completely hidden, it changes to stopped.
Stop: when an Activity is not visible, it is "STOPPED. This Activity will still store all its status and member information in the memory. However, when memory is needed elsewhere, it is most likely to be released. When an Activity is stopped, a very important step is to save the data and the current UI status. Once an Activity exits or is disabled, it will become available.
Waiting for use: after an Activity is killed and put in front, it is waiting for use. To be used, Acitivity is removed from the Activity stack and needs to be restarted before display and availability.
Four loading modes of activity
In multi-activity development of android, there may be many ways to jump between activities. Sometimes it is common to generate a new instance and sometimes you want to jump to an original activity instance, instead of generating a large number of repeated activities. The loading mode determines the method to start a jump to an original Activity instance.
In android, there are four activity startup modes:
· Standard: standard mode. A new instance is generated when the startActivity () method is called.
· SingleTop: if an instance already exists at the top of the Activity stack, a new instance is not generated, but the newInstance () method in the Activity is called. If it is not at the top of the stack, a new instance is generated.
· SingleTask: This instance will be generated in a new task. This instance will be used for each call in the future and no new instances will be generated.
· SingleInstance: this is basically the same as singleTask. There is only one difference: In this mode, only the Activity instance can exist in the task of the activity instance, but not other instances.
You can set these startup modes in the AndroidManifest. xml file of the function list to set the launchMode attribute.
Some symbols can be used in related Code. For example, if you want to enable only one instance, you can use Intent. the FLAG_ACTIVITY_REORDER_TO_FRONT flag indicates that if the activity has been started, no new activity will be generated. You just need to add the activity instance to the top of the stack. Copy code



The loading mode of an Activity is subject to the interaction control between the Flag set in the Intent object that starts the Activity and the feature value of the Activity element in the manifest file.
The following are some features that affect the loading mode:
The core Intent flags include:

  FLAG_ACTIVITY_NEW_TASK
  FLAG_ACTIVITY_CLEAR_TOP
  FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
  FLAG_ACTIVITY_SINGLE_TOP


Core features include:

  taskAffinity
  launchMode
  allowTaskReparenting
  clearTaskOnLaunch
  alwaysRetainTaskState
  finishOnTaskLaunch


Differences between the four loading modes
Difference between tasks
Generally, the target task of the activity of "standard" and "singleTop" is in the same task as the receiver of the received Intent, which is equivalent to who calls it, it is in the same Task.
Unless Intent includes the FLAG_ACTIVITY_NEW_TASK parameter. If the FLAG_ACTIVITY_NEW_TASK parameter is provided, it is started into another task.
"SingleTask" and "singleInstance" always take the activity to be started as the root element of a task and they will not be started into another task.
Whether multiple instances are allowed
"Standard" and "singleTop" can be instantiated multiple times and can exist in different tasks. In such instantiation, a task can include multiple instances of an activity;
"SingleTask" and "singleInstance" only generate one instance and are the root element of the task.
SingleTop requires that if an instance of the Activity to be created at the top of the stack is created when the intent is created, the intent will be sent to the instance without creating a new instance.
Whether other activities are allowed to exist in this task
"SingleInstance" occupies only one task, and other activities cannot exist in that task;
If it starts a new activity, regardless of the launch mode of the new activity, the new activity will run in other tasks (like adding the FLAG_ACTIVITY_NEW_TASK parameter ).
The other three modes can coexist with other activities.
Whether to generate a new instance every time
"Standard" generates a new activity instance for each Intent startup;
If the activity of "singleTop" is at the top of the stack of the task, no new instance of the activity will be generated, and the instance at the top of the stack will be directly used. Otherwise, the instance of the activity will be generated.
For example:
Now the task stack element is A-B-C-D (D at the top of the stack), at this time to D send a start intent, if D is "standard", then generate a new instance of D, stack to A-B-C-D.
If D is singleTop, no new instance of D will be produced and the stack status remains A-B-C-D
If Intent is sent to B at this time, a new instance of B will be generated no matter whether the launchmode of B is "standard" or "singleTop, stack status changes to A-B-C-D-B.
"SingleInstance" is the only activity in the stack where it is located. It will be reused every time.
If "singleTask" is on the top of the stack, intent is accepted. Otherwise, the intent will be discarded, but the task will still return to the foreground. When an existing activity instance processes a new intent, the onNewIntent () method is called. If an intent generates an activity instance, the user can return to the previous status through the back key; if an existing activity is used to process this intent, you cannot press the back key to return the previous status.
-----------------------------------
Ii. Service Details

The service can be used in multiple applications. For example, when the user starts other activities during multimedia playback, the program must continue playing the video in the background, for example, detecting file changes on the SD card, or record the changes in your geographic information location in the background. In short, the service is always hidden in the back.

The Service runs in the background for a period of time and does not interact with the application components. Each Service must be declared in manifest through <service>. It can be started through contect. startservice and contect. bindserverice.

Like other application components, the Service runs in the main process. This means that if the service requires a lot of time-consuming or congested operations, it needs to be implemented in its subthread.

The two service modes (startService ()/bindService () are not completely separated ):

The Local Service is used inside the application.

It can be started and run until someone stops it or it stops it. In this way, it starts by calling Context. startService () and ends by calling Context. stopService. It can call Service. stopSelf () or Service. stopSelfResult () to stop itself. No matter how many times the startService () method is called, you only need to call stopService () once to stop the service.

It is used to implement some time-consuming tasks of the application itself, such as querying the upgrade information. It does not occupy the application, such as the thread to which the Activity belongs, but is executed in the single-thread background, so that the user experience is better.
Remote Service is used between applications in the android system.

It can perform program operations through APIS defined and exposed by itself. The client establishes a connection to the service object and calls the service through that connection. Connection to call the Context. bindService () method to establish, to call Context. unbindService () to close. Multiple clients can be bound to the same service. If the service is not loaded yet, bindService () loads it first.

It can be reused by other applications, such as the weather forecast service. Other applications do not need to write such services and can call existing services.

 

Lifecycle

Using context. startService () to start a Service will experience:

Context. startService ()-> onCreate ()-> onStart ()-> Service running

Context. stopService () |-> onDestroy ()-> Service stop

If the Service is not running, android first calls onCreate () and then onStart (). if the Service is already running, only onStart () is called (), therefore, the onStart method of a Service may be called multiple times.

When stopService is used, onDestroy is used directly. If the caller directly exits without calling stopService, the Service will always run in the background. After the Service caller starts up again, the Service can be closed through stopService.

Therefore, the life cycle for calling startService is onCreate --> onStart (which can be called multiple times) --> onDestroy
Start the Service using context. bindService:

Context. bindService ()-> onCreate ()-> onBind ()-> Service running

OnUnbind ()-> onDestroy ()-> Service stop

OnBind returns an IBind interface instance to the client. IBind allows the client to call back the Service methods, such as obtaining the Service running status or other operations. At this time, the caller (such as Activity) will be bound with the Service, and the Context will exit, and Srevice will call onUnbind-> onDestroy to exit accordingly.

Therefore, the life cycle of calling bindService is onCreate --> onBind (only once, cannot be bound multiple times) --> onUnbind --> onDestory.

During each Service enabling and disabling process, only onStart can be called multiple times (through multiple startService calls), other onCreate, onBind, onUnbind, onDestory can only be called once in a lifecycle.


When the service is started, there are two additional modes based on the onStartCommand return value:

1. START_STICKY is used to display start and stop services.

2. START_NOT_STICKY or START_REDELIVER_INTENT is used in the mode where a command needs to be processed.

The service cannot run on its own. You must call the Context. startService () or Context. bindService () method to start the service. Both methods can start the Service, but their usage is different.

1. Use the startService () method to enable the service. There is no relation between the caller and the service. Even if the caller exits, the Service continues to run.

If you plan to use the Context. startService () method to start the service, when the service is not created, the system will first call the onCreate () method of the service and then call the onStart () method.

If the service has been created before the startService () method is called, multiple call of the startService () method will not lead to multiple creation of the service, but will lead to multiple calls of the onStart () method.

A service started using the startService () method can only end the service by calling the Context. stopService () method. The onDestroy () method is called when the service ends.

2. Use the bindService () method to enable the Service. The caller and the service are bound together. Once the caller exits, the service is terminated. This feature has the following features: "The caller does not want to generate at the same time and must die at the same time.

OnBind () calls back this method only when the Context. bindService () method is used to start the service. This method is called when the caller binds to the service. When the caller and the service are already bound, multiple calls to the Context. bindService () method will not cause this method to be called multiple times.

When the Context. bindService () method is used to start a service, only the onUnbind () method can be called to release the caller and the service. When the service ends, the onDestroy () method is called.

Take a look at the official comparison process:

The official documentation tells us that a service can start and bind at the same time. In this case, the system will keep the service Running State if the service has been started or the BIND_AUTO_CREATE flag is set. If none of the conditions are met, the system will call the onDestory method to terminate the service. All cleanup tasks (terminate the thread, anti-register the receiver) are completed in onDestory.

Processes with services have a high priority.

The official documentation tells us that the Android system will try to keep the process with service running as long as the service has been started (start) or the client connection (bindService) to it. When the memory is insufficient, it must be maintained. Processes with services have a high priority.

1. if the service is calling the onCreate, onStartCommand, or onDestory method, the process used for the current service changes to the foreground process to avoid being killed.

2. if the current service has been started, processes with it have lower priority than processes visible to users, but are more important than invisible processes, this means that the service is generally not killed.

3. If the client has been connected to the service (bindService), the process with the Service has the highest priority and can be considered as visible.

4. If the service can use the startForeground (int, Notification) method to set the service to the foreground state, the system considers the service to be visible to the user and will not killed the service when the memory is insufficient.

If other application components run in the same process as services and activities, the importance of the process will be increased.

Local service

1. Local services that do not need to interact with the Activity

Copy code

Activity:

Copy code

Add the following in AndroidManifest. xml:

Copy code

Otherwise, the system prompts "com. demo. SERVICE_DEMO" cannot be found in new Intent when starting the service ".

This type of local service that does not need to interact with the Activity is the best example of using startService/stopService.

During the first startService operation, you can find that onCreate and onStart will be called. Before there is no stopService, only onStart will be called no matter how many times startService is clicked. The stopService calls onDestroy. Click stopService again and you will find that it does not enter the service lifecycle, that is, it will not call onCreate, onStart and onDestroy.

OnBind is not called in startService/stopService.

2. Interaction between local services and activities

For this case, the official sample (APIDemo \ app. LocalService) is the best example:

Copy code

Here we can find that onBind needs to return an IBinder object. That is to say, unlike the LocalService in the previous example,

1. added a public internal class to inherit the Binder, and added the getService method to return the current Service object;

2. Create an IBinder object -- the new Binder internal class;

3. The onBind method returns the IBinder object.

Activity:

Copy code



Obviously, a ServiceConnection class is added, and onServiceConnected (get Service object from IBinder) and onServiceDisconnected (set Service to null) are implemented ).

The bindService and unbindService Methods Operate on this ServiceConnection object.

Add the following content to AndroidManifest. xml:

Copy code

There is nothing special here, because the service does not need any special action, so it just declares the service, and the activity is no different from the common one.

During running, we found that the call order is as follows:

BindService:

1. LocalService: onCreate

2. LocalService: onBind

3. Activity: onServiceConnected

UnbindService: Only onDestroy is called.

It can be seen that onStart is not called, and the reason why onServiceDisconnected is not called is described in the comments of the code above.


------------------------
Iii. Explanation of Broadcast Receiver


BroadcastReceiver is used to receive broadcast Intent asynchronously. There are two main categories for receiving broadcasts:

· Normal broadcast Normal broadcasts (sent using Context. sendBroadcast () is completely asynchronous. They all run in an undefined order, usually at the same time. This will be more effective, but it means that the consumer cannot contain the results to be used or the APIs to be aborted.

· Ordered broadcast Ordered broadcasts (sent using Context. sendOrderedBroadcast () is sent to a receiver each time. The so-called order means that each worker can be propagated to the next worker after execution, or the propagation can be completely aborted without being propagated to other worker workers. The sequence of worker er running can be controlled by android: priority in matched intent-filter. When priority has the same priority, worker er runs in any order.

Note that, even in Normal broadcasts, the system may resume one transmission to a receiver in some cases. In particular, a worker er may need to create a process. To avoid system overload, only one worker er can be run at a time.

Broadcast Receiver does not provide a visual interface for displaying Broadcast information. Notification and Notification Manager can be used to display the broadcast information content, icons, and vibration information.

Lifecycle

A BroadcastReceiver object is valid only when onReceive (Context, Intent) is called. After the function is returned, this object is invalid and the lifecycle ends.

Therefore, we can see from this feature that the onReceive (Context, Intent) function called cannot have too many time-consuming operations and cannot be executed using threads. For time-consuming operations, start service. Because BroadcastReceiver may be invalid when other asynchronous operations return results.

Send Broadcast

It is relatively simple to broadcast events. To build Intent objects, you can call the sendBroadcast (Intent) method to send broadcasts. In addition, there are sendOrderedBroadcast (), sendStickyBroadcast () and other methods. Please refer to the API Doc.

1. new Intent with action name

Intent intent = new Intent (String action );

Or just new Intent, and then

Intent. setAction (String action );

2. After the set data and so on are ready, in activity,

SendBroadcast (Intent); // send Broadcast

Receive Broadcast

It is implemented by defining an inherited BroadcastReceiver class, inheriting this class, overwriting its onReceiver method, and responding to events in this method.

Copy code

Register aggreger

There are two registration methods:

1. static mode: Define the receiver in the application of AndroidManifest. xml and set the action to be received.

Copy code

2. In the dynamic mode, the function is called in the activity to register, which is similar to static content. One parameter is the receiver, and the other is the IntentFilter, which contains the action to be received.

Copy code

A single receiver can receive multiple actions, that is, multiple intent-filters can exist. You need to judge intent. getAction (action name) in onReceive.

I personally recommend that you use the static registration method. The system manages the handler, and all the schedulers in the program can be clearly viewed in xml. The dynamic registration method is hidden in the code, which is hard to find.

In addition, you must note that you must call the Context. unregisterReceiver () method before exiting the program. Generally, registration is performed in onStart () of the activity, and cancellation is performed in onStop. Official reminder: If you have registered in Activity. onResume (), you must log out of Activity. onPause.

Permission

To receive certain actions, you must add the corresponding permission in AndroidManifest. xml. For example, to receive SMS:

Copy code

The following code shows the call handler for Dynamic Registration of broadcast processing for incoming calls:

One way is to directly read intent. getStringExtra ("incoming_number") to get the incoming call number:

Copy code

During operation, it is found that the incoming call number can be obtained only when the bell rings, and neither the answer nor the end of the call can be obtained successfully, and the display is null.

Another method is to monitor the status change through the onCallStateChanged of the PhoneStateListener:

Copy code

During running, it is also found that the incomingNumber is obtained as blank when it is answered and hung up.

Because the listener changes the call status, the caller will be called three times.

To listen to the call status, you must add the following permissions:

Copy code

==============

Summary:

1. For the intent object of sendBroadCast, you need to set its action name;

2. It is recommended to explicitly specify the consumer in the configuration file AndroidManifest. xml;

3. One consumer can receive multiple actions;

4. Each time you receive a broadcast, a new broadcast receiving object is generated and onReceive is called again;

5. Do not handle too many logic problems in BroadCast. It is recommended that complicated logic be handled by Activity or Service.



--------------------------------------------
Iv. Detailed description of Content Provider

ContentProvider is one of the four main components in Android. It is mainly used for external data sharing, that is, using ContentProvider to share the data in the application to other applications for access. Other applications can use ContentProvider to operate on the data in the specified application. ContentProvider is divided into system and custom data, such as contacts and images.

The data operation package in android contains:

The first three data operations of file, sqlite3, Preferences, ContectResolver, and ContentProvider are only for data in the current application. The program cannot use these three methods to operate on data in other applications.

In android, ContectResolver and ContentProvider are provided to operate data of other applications.

Usage:

One application implements ContentProvider to provide content to other applications for operations,

An application uses ContentResolver to operate other application data. Of course, it can also be used in its own application.

The following section provides a general overview of ContentProvider in Google Doc:

The content provider provides specific application data to other applications. The content provider inherits from the ContentProvider base class and implements a set of standard methods for other applications to access and store the data it manages. However, the application does not directly call these methods, but uses a ContentResolver object to call its method as an alternative. ContentResolver can communicate with any content provider to manage all related interactive communication.

1. ContentProvider

Android provides some main data types of ContentProvider, such as audio, video, images, and private address book. You can find some ContentProvider provided by android in the Android. provider package. By obtaining these contentproviders, You can query the data they contain, provided that you have obtained the appropriate read permission.

Main Methods:

Public boolean onCreate () is called when ContentProvider is created

Public Cursor query (Uri, String [], String, String [], String) is used to query the ContentProvider of a specified Uri. A Cursor

Public Uri insert (Uri, ContentValues) is used to add data to the ContentProvider of the specified Uri.

Public int update (Uri, ContentValues, String, String []) is used to update data in the ContentProvider of the specified Uri.

Public int delete (Uri, String, String []) is used to delete data from the specified Uri's ContentProvider.

Public String getType (Uri) is used to return the MIME type of the data in the specified Uri.


* If the operated data belongs to the set type, the MIME-type string should start with vnd. android. cursor. dir.

For example, if the Uri of all person records is content: // contacts/person, the returned MIME-type string is "vnd. android. cursor. dir/person ".

* If the data to be operated belongs to a non-set type, the MIME-type string should start with vnd. android. cursor. item.

For example, if the Uri of the person record whose id is 10 is content: // contacts/person/10, the returned MIME-type string should be "vnd. android. cursor. item/person ".

2. ContentResolver

When an external application needs to add, delete, modify, and query data in ContentProvider, you can use the ContentResolver class to complete the operation. To obtain the ContentResolver object, you can use the getContentResolver () provided by Context () method.

ContentResolver cr = getContentResolver ();

The methods provided by ContentResolver and the methods provided by ContentProvider correspond to the following methods.

Public Uri insert (Uri uri, ContentValues values) is used to add data to the ContentProvider of the specified Uri.

Public int delete (Uri uri, String selection, String [] selectionArgs) is used to delete data from the specified Uri's ContentProvider.

Public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs) is used to update data in the ContentProvider of the specified Uri.

Public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder) is used to query the ContentProvider of a specified Uri.




3. Uri

Uri specifies the ContentProvider to be operated. In fact, you can regard a Uri as a URL. We divide the Uri into three parts.

The first part is "content ://". It can be viewed as "http: //" in the URL ://".

The second part is the host name or authority, which is used to uniquely identify the ContentProvider. External applications need to find it based on this identifier. It can be seen as the host name in the URL, such as "blog.csdn.net ".

The third part is the path name, which indicates the data to be operated. It can be seen as the content path in the URL segment.

 
---------------------------------

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.