Knowledge point dry--talk about the difference between service and thread in Android

Source: Internet
Author: User

The old saying goes well: "Time is money, cornucopia." "An inch of time and an inch of gold as expensive, and an inch of gold is difficult to buy an inch of time." Metaphor time is very valuable. This statement from the Tang Dynasty Wang "White Deer Hollow Two first", "Reading does not feel spring deep, time is money." is not the Taoist to draw a smile, Zhou sentiment hunsworth is seeking. "Warning US time is money, cornucopia. We should cherish time, but not wasting time.
Another way is "an idle youth, needy age", tell us not to waste youth, through the ages, there are many people, when they come to the age of gray-haired, read this poem, will be deeply shocked, so it will be widely read, and spread to today. Confucius, a big educator, also once pointed out: "90 without the smell of Yan, and also not afraid of it." "What he means is that if the person is 40 years old, at most 50 years old, and has not done something in society, he will be like this all his life." Because of this, the national hero Yue Fei in his masterpiece "Azolla" in the use of this maxim to express his attitude to life: "30 fame dust and soil, 8,000 miles cloud and month." Mo lightly, white a young head, empty mournful. He has given his short and glorious life a powerful inspiration and encouragement to posterity.
So everyone should cherish the time, do not waste degrees of youth.

For Android beginners, often do not know when to use the service, when the use of thread, can use the thread to solve the problem, often start a service to work, and need to use the service to better solve the problem, The use of thread is also persisting, resulting in a number of issues that affect performance and the efficiency of program execution. Today we'll talk about what the service and thread are, the difference, the use of the scene and so on, so that the students unfamiliar with them can better grasp this knowledge point, to avoid the wrong use later. Everybody ready, the old driver to drive, have Carsick? If you are ready to get carsick medicine, the speed may be faster, and some bumps, help to sit well, we drove.

In fact, they do not have a half-penny relationship.

1. What is the service? (1), definition

Service is one of the four components of Android. When it is defined, if the android:process attribute is not specified when registering in Androidmanifest.xml, then it is a local service, and the corresponding service and application are running in a process, The name of the process is represented by the package name of the app, for example, the package name is "Xxx.xxx.xxx", the process name is also "Xxx.xxx.xxx", and runs on the main thread (or called the thread, UI thread, which we call the main thread in this article). such as: Oncreate,onstart These functions are run on the main thread when they are called by the system. If the android:process attribute is not specified in Androidmanifest.xml, for example, when the definition android:process= ": Xxxservice" is set, then it is a remote Service, It runs in a separate process with the process name "package Name: Xxxservice", and its corresponding Service is also running on the main thread of this standalone process. That is, either the local service or the remote service, it is always running on the main thread.
Here is a knowledge point, is the android:process attribute, in the definition of remote service, there are often two ways,
One is for example, android:process= ": Xxxservice", then its process name is "package name: Xxxservice".
Another is the definition, android:process= "Yyy.yyy,yyy.yyyservice", that is, the process name is arbitrary, but must be lowercase letters, generally we define, "package name. Yyyservice".
What is the difference between the two definitions?
The former contains a colon and begins with the current package name, indicating that the new process is private to the application and that other applications should be inaccessible or interact with it. The latter, the service process, will run in the global process and open for all applications, allowing some means to access the functionality it provides in other applications. This is the difference between the two, so generally if the service is not provided externally, and for the sake of better security, it is recommended to use a colon-like way.

(2), Service life cycle

Service as one of the four components of Android, and activity is the same, there is a life cycle, it is generally seen as running in the background, no interface "Activity."
Its life cycle consists of the following methods,
OnCreate
Create a service
OnStart (or Onstartcommand)
Start Service
OnDestroy
Destruction Services
Onbind
Binding Service
Onunbind
Unbind Service

The method to start or bind the service corresponds to the
StartService ()
Start the service
Start the service using the StartService method.
If a service is started by an activity using the StartService method, then whether or not activity uses bindservice binding or Unbindservice to unbind to the service, The service runs in the background, but it still runs on the main thread. If the service is started multiple times by the StartService method, the OnCreate method is only called once, OnStart will be called multiple times (corresponding to the number of calls StartService), and only one instance of the service will be created. The service will continue to run in the background, even if the activity that started it has exited, until an activity calls StopService, or the Stopself method itself calls to end the services. Of course, if the system resources are insufficient, the Android system may end the service.

Bindservice ()
Binding Service
Start the service using the Bindservice method.
If a service is started by an activity call Bindservice method binding, the OnCreate method is called only once, and the OnStart method is not invoked, no matter how many calls Bindservice calls. When the connection is established, the service will run until the call to the Unbindservice method disconnects or the Context of the previous call to Bindservice does not exist (such as when the activity is finished). The system will automatically stop the service and the corresponding OnDestroy will be called.

One of the more complex uses is to start the service using both the StartService and Bindservice methods. If a service is also started and bound, the service will always run in the background. And no matter how it is called, OnCreate is always called only once, how many times the service's onstart is called, and how many times the StartService is called. Calling Unbindservice will not stop the service, but it must be called by the outside activity call StopService or stopself to stop the services.

In addition, there are methods for stopping services and unbinding services,
StopService ()
Close Service

Unbindservice ()
Unbind Service

2. What is thread? (1), definition

Thread is the smallest unit of program execution, and it is the basic unit for allocating CPUs. You can use the Thread to perform some asynchronous operations. The thread is divided into the main thread and the child thread. The time-consuming operations we typically do are placed in child threads, and the functionality of UI refreshes is placed in the main thread.

(2), Thread life cycle

A thread is a process that executes dynamically, and it also has a process from generation to death.

It has a life cycle of five states:
New (new Thread)
When you create an instance of the thread class, the thread enters a new state or is not in the startup state.
For example: Thread thread=new thread ();

Ready (runnable)
The thread has been started and is waiting to be allocated to the CPU time slice, which means that the thread is waiting in the ready queue to get CPU resources.
For example: Thread.Start ();

Run (running)
The thread obtains the CPU resources that are executing the task and is running the run () method, and the thread will run until the end until this thread automatically discards the CPU resources or has a higher priority thread entry.

Death (dead)
When a thread executes or is killed by another thread, the thread goes into a dead state, and the thread is no longer ready to wait for execution.
Natural termination: Terminates after running the run () method normally
Abort: Call the Stop () method to let a thread terminate the run

Clogging (blocked)
For some reason, the running thread is getting out of the CPU and pausing its own execution, which goes into a blocked state.
Sleeping: Use the sleep (Long T) method to put the thread into sleep mode. A sleeping thread can go into a ready state at the specified time.
Waiting: Call the Wait () method. (In this state, call the Motify () method line routines back to the ready state)
Blocked by another thread: Call the Suspend () method. (In this state, call the Resume () method to restore)

The common methods are:
void Run ()
This method must be implemented when creating subclasses of the class.

void Start ()
Start thread

static void sleep (Long T)
Frees the CPU's execution power for t seconds, but does not release the lock.

final void Wait ()
Release the execution of the CPU, release the lock

static void Yied ()
You can temporarily pause the current thread (let the thread release the resource)

3. Usage Scenarios

The above definition is visible, and the two are not related. First of all, why there is a service this component, why it is related to thread's own shortcomings, because only using thread does not solve the problem. We know that both of them are performing tasks in the background and have no interface.
When we use thread to start a sub-thread to do some time-consuming operations, this child thread is typically initiated by the activity (if there is no service component), and the thread sub-thread runs independently of the activity, then when an activity is After finish, if you do not actively stop the thread or thread in the Run method is not finished, thread will not end, it will continue to execute. So there's a problem here: When the Activity is finished, you no longer have a reference to the Thread, and you can't control it.
On the other hand, you have no way to control the same thread in different Activity.
For example, if your thread needs to be connected to a server for a certain amount of time, it needs to be running after the Activity exits. At this point you have no way to control the thread that was created by the activity in your active activity, so that this sub-thread is equivalent to a "wild thread" and you cannot monitor and control it.
At this time the value and significance of the service is reflected, you can create and start a service, in the service can be created, run and control the thread, do not worry about the service exit after the no longer control thread, Because the service runs in the background, it does not have an activity interface and does not "explicitly" exit. This solves the problem of using thread above.
By the above instructions, you should be aware of their respective duties, as well as the use of the scene.

4. Precautions

There are also a lot of pits to keep in mind when using the service.
(1), when calling Bindservice binding to the service, it should be guaranteed to call Unbindservice unbind when exiting, this is a good habit, beginning and ends. Although the Activity is automatically released when the binding is terminated, and the service stops automatically;
(2), should pay attention to use StartService start service, must use StopService stop service, regardless of whether you use Bindservice;
(3), while using StartService and bindservice to notice, service termination, need to unbindservice and stopservice simultaneously call, can terminate Service, regardless of StartService and The order in which Bindservice is called, if Unbindservice is called first, the service does not terminate automatically, then the service stops after calling StopService, and if StopService is called first, the service will not terminate, and then call Unbindservice or the Context of the previous call to Bindservice does not exist (such as when the activity is finished) after the service will automatically stop;
(4), in the SDK 2.0 and later versions, the corresponding OnStart has been upgraded to Onstartcommand, but the previous OnStart still valid. This means that if you are developing an application with an SDK of 2.0 and later, you should use Onstartcommand instead of OnStart.
(5), you can also register Broadcastreceiver in the Service, in other places by sending broadcast to control it, these are not the Thread to do.

5. Summary

The above visible service and thread have different definitions and lifecycles in their respective fields, but they have little to do with it, but they need to be able to work together to solve some of the android problems. I hope we can understand how they are used, and don't be confused.


This public number will be based on the knowledge of how to push a variety of technical dry or fragmented Android technologies, as well as the experience and knowledge that the old drivers have trodden on in their daily work, and will occasionally summarize the new technologies they are learning to share. A little bit of dry-day knowledge to make the most of your debris time.

Knowledge point dry--talk about the difference between service and thread in Android

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.