You will gain the following knowledge:

  1. The basic concept
  2. The life cycle
  3. And the Thread distinction
  4. IntentService
  5. Different from the Activity
  6. use

What is Service

1.1 What is Service

  • A Service is an application component that can perform operations in the background for a long time without a user interface.

  • A service can be started by another application component (such as an Activity). Once started, the service runs in the background, even if the component that started the service is destroyed (start mode).

  • Components can be bound to services to interact with them or even perform interprocess communication (IPC).

1.2 Services are often called “background services”

  • Among them, the word “background” is relative to the foreground, specifically refers to: its own operation does not depend on the user visibleUIinterface
  • So, in terms of actual business requirements,ServiceApplicable scenarios should meet the following conditions:
  1. Does not depend on user visibilityUIInterface (of course, this is actually not absolute, such as the front deskServiceEven withNotificationInterface used in combination)
  2. Features that run for a long time and run in the main thread

1.3 Service Process

  • The service process is throughstartService()Method, but is not a foreground or visible process. For example, playing music in the background or downloading music in the background is a service process.
  • The system keeps them running unless there is not enough memory to keep all foreground and visual processes running.

Life cycle

2.1 Service Life Cycle

  • Let’s take a look firstServiceThe basic flow of the life cycle

2.2 Two Ways to Enable the Service

2.2.1 startService ()

  • Define a class that inherits Service

  • Configure the Service in the manifest.xml file

  • Start the service using the startService(Intent) method of the Context.

  • The stopService(Intent) method of the Context is used to close the service.

  • This startup mode does not affect app killing or Activity destruction, and the service will not stop the destruction.

2.2.2 bindService ()

  1. createBindServiceServer side, inheritanceServiceAnd inside the class, create an implementationIBinderInterface and provide public methods to the client (Activity) call.
  2. fromonBinder()The callback method returns thisBinderInstance.
  3. On the client side (ActivityFrom)onServiceConnection()The callback method parameter is receivedBinderThrough theBinderObject accessibleServiceInternal data.
  4. inmanifestsRegistered inBindService, called in the clientbindService()Method to enable bindingService, the callunbindService()The unbind method is used to unbindService
  5. The startup mode depends on the client lifecycle when the clientActivityWhen destroyed, no callunbindService()Method,ServiceThey will also stop destroying it.

2.3 How to start a Service? What are the differences? How to stop a Service

  • During the life cycle of a Service, fewer methods are called back than activities, only onCreate, onStart, onDestroy, onBind, and onUnbind.

  • There are generally two ways to start a Service, and they have different effects on the Service life cycle.

2.3.1 throughstartService

  • ServiceGo throughonCreate 到 onStart, and then in the running state,stopServiceIs called whenonDestroyMethods.

2.3.2 throughbindService

The Service will run onCreate and then call onBind, where the caller is bound to the Service. Srevice calls onUnbind -> onDestroyed when the caller exits.

2.3.3 What should be noted is that if these methods are interwoven, what will happen?

  • One principle is that the onCreate method of a Service is called only once, that is, no matter how many times you call startService and bindService, the Service is created only once.

  • If you bind first, run the onStart method of the Service directly when you start. If you bind first, run the onBind method directly when you bind.

  • If bindService is called and stopService is called, the service will not call onDestroy and will not stop. You can only call UnbindService and the service will be destroyed

  • If a service is started by startService and startService is called several times, the service calls onStart multiple times. If stopService is called multiple times, the Service will only call onDestroyed once.

  • If a service calls bindService multiple times after being started by bindService, the service will only call onBind once. Calling unbindService more than once throws an exception.

Chapter three: Services and Threads

3.1 Differences between Services and Threads

  • A thread is the smallest unit of execution, and it’s the basic unit of CPU allocation. In Android, what we call the main thread, the UI thread, is another type of thread. Of course, threads can also perform time-consuming asynchronous operations.

  • And service, remember, it’s a special mechanism in Android, it runs on the main thread, so it can’t do time-consuming things, it’s hosted by the system process, but it’s also a lightweight IPC communication, Because an activity can be bound to a service, it can communicate data with the service.

  • In addition, in one case, the activity and service are in different processes, so the data communication between them needs to be operated through the IPC interprocess communication mechanism.

3.1.2 The second point is in the actual development process

  • In Android, a thread is a worker thread, a background thread, a thread that does something time-consuming, and the main thread is a special thread that just handles the drawing of some UI thread, and you can’t do anything time-consuming in the UI thread, so that’s the most basic and important thing. (This is the application of Thread in the actual development process)

  • Service is one of the four components of Android, and generally runs in the main thread. Therefore, service cannot perform time-consuming operations. Otherwise, the system reports ANR exceptions (full name of ANR: Application Not Responding), which means that the program cannot respond.

  • If you must perform time-consuming operations within a service, be sure to start a separate thread to do them.

3.1.3 The third point is application scenarios

  • When you need to perform time-consuming networking, or this type of file data query, or any other blocking UI thread, you should use worker threads, which is to start a child thread.

  • This ensures that the UI thread is not tied up and the user experience is not affected.

  • For service, we often need to run in the background for a long time and do not need to interact with each other before using the service. For example, we can play music in the background, enable the statistics of weather forecast and some data statistics, etc.

3.2 Why Service instead of Thread

  • A Thread runs independently of an Activity. That is, after an Activity finishes, the Thread will continue executing if it does not stop the Thread or if the run in the Thread does not complete.

  • Therefore, there is a problem: when the Activity is finished, you no longer hold a reference to the Thread.

  • On the other hand, you cannot control the same Thread in different activities.

3.3 Can Time-consuming Operations be Performed in the Service

  • Service cannot perform time-consuming operations (network requests, copying databases, large files)
  • ServiceIt is not a separate process, nor is it a separate thread, it is dependent on the main thread of the application, that is, it is not recommended in most casesServiceWrite time-consuming logic and operations (e.g., network requests, copying databases, large files) that would otherwise causeANR
  • If you want to perform time-consuming tasks in a service. There are the following solutions:
  1. Start a child thread in a service

  2. You can use IntentService to manage the service asynchronously

3.4 Check whether the Service is executed on the main Thread

  • By default, services and activities run in the main thread of the current app process if they are not displayed.

  • The Service and the Activity are in the same Thread, and by default, the main Thread (UI Thread) is in the same Thread for the same app.

  • In special cases, you can configure the process of the service execution in the manifest file so that the service can execute in another process

3.4.1 track inonStartCommandmethodflagSet toSTART_STICKY ;

3.4.2 is set in XMLandroid:priority

<! <service android:name=".myService "Android :priority="2147483647" > </service>Copy the code

Rule 3.4.3 inonStartCommandMethod as the foreground process

public int onStartCommand(Intent intent, int flags, {int startId) Notification Notification = new Notification (R.m ipmap. Ic_launcher, "service is running," System. CurrentTimeMillis ()); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,notificationIntent,0); RemoteViews remoteView = new RemoteViews(this.getPackageName(),R.layout.notification); remoteView.setImageViewResource(R.id.image, R.mipmap.ic_launcher); remoteView.setTextViewText(R.id.text , "Hello,this message is in a custom expanded view"); notification.contentView = remoteView; notification.contentIntent = pendingIntent; startForeground(1, notification); return Service.START_STICKY; }Copy the code

IntentService

4.1 What is IntentService

  • IntentServiceServiceSubclass of, than ordinaryServiceAdded additional features.
  • We often useServiceThere are two problems:
  1. ServiceInstead of specifically starting a single process,ServiceIn the same process as the application in which it resides
  2. ServiceIt is not dedicated to a new thread, so it should not be inServiceDirect processing of time-consuming tasks in

4.2 Characteristics of IntentService

  • A separate worker thread is created to handle all Intent requests

  • A separate worker thread is created to handle the code that implements the onHandleIntent() method without having to deal with multithreading

  • After all requests are processed, IntentService stops automatically, without calling stopSelf() to stop the Service

  • Provide the default implementation for Service onBind(), which returns NULL

  • Provide a default implementation for Service onStartCommand that adds the request Intent to the queue

4.3 Difference between Service and IntentService

4.3.1 ServiceIt is used for background services

  • The concept of Service was introduced when applications were hung in the background to ensure that some of the application components still worked

  • A Service is not a separate process, nor is it a separate thread. It is dependent on the main thread of the application. In other words, it is not recommended to write time-consuming logic and operations in a Service, which can cause ANR.

4.3.2 When we write the time consuming logic, have to beserviceTo manage, you need to introduceIntentService 。

  • IntentService inherits from a Service, so it contains all the features of the Service, as well as the life cycle of the Service.

  • IntentService, unlike a service, opens a thread inside the onCreate operation so that you can perform your time-consuming operation.

4.3.3 use:

Override protected Abstract void onHandleIntent(Intent Intent)

4.3.4 IntentServiceCan handle asynchronous requestsService

  • To use it, you simply inherit IntentService and override the onHandleIntent(Intent) method in it to receive an Intent object and stop itself when appropriate (usually when the work is done).

  • All requests are processed in a worker thread, and they alternate (but do not block the main thread), executing only one request at a time.

4.3.5 is a message-based service

  • Each time you start the service, instead of doing your job immediately, you first create the corresponding Looper, Handler, and Message object attached to the client’s Intent in MessageQueue.

  • Looper then gets the Intent object when it finds a Message by calling your handler in onHandleIntent((Intent)msg.obj) and then stopping its service.

  • Meaning that the lifecycle of an Intent is consistent with the task you’re handling, so this class is great for downloading tasks, and the service itself will exit when the download task is complete.

4.3.6 summaryIntentServiceThe characteristics are:

  • A separate worker thread is created to handle all Intent requests;

  • A separate worker thread is created to handle the code that implements the onHandleIntent() method without having to deal with multithreading;

  • IntentService stops automatically after all requests are processed, without calling stopSelf() to stop the Service;

Service and Activity

5.1 How to bind an Activity to a Service and how to start the corresponding Service in an Activity

  • An Activity is bound to a service by bindService(Intent Service, ServiceConnection Conn, int Flags). When the binding is successful, the Service passes the proxy object to Conn via a callback, and we get the Service proxy object provided by the Service.

  • You can start a Service in an Activity using the startService and bindService methods. In general, if you want to obtain Service objects, you must use bindService() method, such as music player, third-party payment, etc.

  • You can use the startService() method if you just want to start a background task.

5.2 Describe the relationship between an Activity, an Intent, and a Service

  • They are among the most frequently used classes in Android development. Activity and Service belong to the four components of Android. They’re both subclasses of ContextWrapper, so they’re kind of brothers.

  • However, they each have their own skills. Activities are responsible for displaying and interacting with user interfaces, and Services are responsible for processing background tasks.

  • An Activity and a Service can pass data between them through an Intent, so you can think of an Intent as a messenger.

5.3 Are Service and Activity on the same thread

The default for the same app is to be in the same Thread, the main Thread.

Can you play toast in Service

  • can
  • There’s one thing about toast: you have to have oneContextContext, whileServiceItself isContextA subclass of
  • So inServiceIt’s totally okay to pop toast in there. Like when we were inServiceAfter completing the download task, you can play a toast to notify the user.

5.5 Interaction mode with Service

5.5.1 Broadcast Interaction

  • The Server sends the current download progress through broadcast. The Client registers the listener of this broadcast. After obtaining the broadcast, the Server resolves the current download progress in the broadcast and updates it to the interface.

  • Define your own broadcasts so that different activities, services, and applications can interact with each other through broadcasts.

5.5.2 File Sharing Interaction

  1. We use theSharedPreferencesTo implement sharing, of course, you can use otherIOIn this way, it is necessary to pay attention to that when reading and writing files, only one party can read and write files at the same time, not both parties can write at the same time.
  2. ServerThe end will write the current download progress into the shared file,ClientThe end reads the download progress in the shared file and updates it to the main interface.

5.5.3 MessengerInteraction (Messenger interaction)

  1. MessengerThe translation refers to the messenger, and it quotes oneHandlerObject to which others can send messages (usingmMessenger.send ( Message msg )Methods).
  2. This class allows cross-process basedMessageCommunication, used on the server sideHandlerTo create aMessengerThe client just needs to get the serverMessengerThe object can then communicate with the server
  3. inServerThe terminal and the Client pass oneMessengerObject, which acts as a sort of information relay through which all information is carried

5.5.4 Customizing Interface Interaction

  1. We do it ourselves through the implementation of the interfaceActivityServiceThe purpose of the interaction is through theActivityServiceBuild a bridge between, so as to achieve the purpose of data interaction, and this kind of implementation andAIDLVery similar
  2. Customize an interface that has an empty method to get the current download progress.ServerThe end uses a class inherited fromBinderAnd implement the interface, overwrite the method of obtaining the current download progress.ClientEnd byServiceConnectionGet the object of the class, so that you can use the method to get the current download progress, and finally achieve real-time interaction.

5.5.5 AIDLinteraction

  1. Remote services generally passAIDLTo implement, can carry out inter-process communication, this service is also called remote service.
  2. AIDLBelong toAndroid 的 IPCMechanism, commonly used for cross-process communication, based on the underlying implementation principleBinderMechanism.

Chapter six: Use

6.1 When is Service used

<service android:enabled="true"/"false" android:exported="true"/"false" android:icon="drawable resource" android:isolatedProcess="true"/"false" android:label="string resource" android:name="string" android:permission="string"  android:process="string" > </service>Copy the code
  • Android :enabled: This service can be instantiated by the system if it is true, but not if it is false. The default is true

  • Android: Exported: If true, components of other applications can also invoke and interact with the service. If false, only applications with the same user ID or the same application can enable or bind to the service. Its default value depends on whether the service has intent filters. If there is no filter, the service can be called only if the exact class name of the service is specified. That is, the service can only be used internally. Other applications do not know its class name. The default value exported in this case is false. On the other hand, a filter means that a service takes into account external usage, and the default exported value is true

  • Android :icon: an icon that represents this service

  • Android :label: the name of the service displayed to the user. If not set, the label attribute is used by default.

  • Path name to the android: name: this service, such as “com. Liangkui. Demo. MyService”. This property is the only one that must be filled in.

  • Other components must have the specified permission to start the service.

  • Android: Process: name of the process that service runs. The default service starts in the main process. (Note: android:process=”:ramote” must have a colon otherwise it will not run)

6.1.1 Experience Summary:

  1. ServiceYou know, doing things behind your back, and you don’t want anyone to know
  2. For example, if you want to know something, you don’t need to ask directly, you can know it from the side. This is theServiceOriginal intention of design

6.1.2 ServiceWhy was it designed

  • According to the definition of Service, we know that we need to put the work that needs to be done in the background for a long time in a Service.

  • Work that cannot be performed in an Activity must be performed in a Service.

  • For example, play music, download, upload large files, and close applications periodically. These functions will stop when the Activity exits and is destroyed, which is clearly not our design, so put them in a Service.

6.2 onStartCommand() Return Value Int Value difference

6.2.1 START_STICKY :

  1. ifserviceThe process was killed and saved. ProcedureserviceIs in the start state, but does not reserve the delivered stateintentObject.
  2. The system then attempts to recreate itserviceBecause the service is in the start state, it must be invoked after the service is createdonStartCommand ( Intent, int, int )Methods.
  3. If no start command is passed to during this periodservice, then parametersIntentWill provide thenull

6.2.2 START_NOT_STICKY :

  1. “Non-sticky.”
  2. When using this return value, if the execution is doneonStartCommandThe service is abnormalkillIf no, the system does not restart the service automatically.

6.2.3 START_REDELIVER_INTENT:

  1. The retransmissionIntent
  2. When using this return value, if the execution is doneonStartCommandThe service is killed by an exception
  3. The system automatically restarts the service and passes in the Intent value.

6.2.4 START_STICKY_COMPATIBILITY:

  1. START_STICKYCompatible version, but does not guarantee that the service iskillWe’ll be able to restart it later.

6.3 Can onstartConmand() perform network operations in the Service lifecycle? How do I perform network operations in a Service?

  • You can go directly toServiceTo perform network operations
  • inonStartCommand()Method to perform network operations

6.4 Improving the Service Priority

  • In the androidmanifest.xml file, you can set the highest priority for intent-filter by android:priority = “1000”. 1000 is the highest value. If the number is smaller, the priority is lower.

  • Raise the Service to foreground level by calling startForeground() in onStartCommand, and then calling stopForeground () in onDestroy.

  • OnStartCommand to manually return START_STICKY.

  • Restart the service by broadcasting in onDestroy.

  1. service + broadcastThe way is whenserviceondestorySends a custom broadcast
  2. When a broadcast is received, restartservice. (Third-party apps or insettingLi – When applying force stop,APPThe process just gets killed,onDestroyMethods cannot be entered, so there is no guarantee that they will be executed.
  • Listening system broadcast judgmentServiceState.
  1. Some broadcasts through the system
  2. For example: mobile phone restart, interface wake up, application state change, etc., monitor and capture, and then judge ourServiceWhether they’re still alive.
  • ApplicationaddPersistentProperties.

6.5 When is the onRebind (Intent) method of a Service Executed

  • If theonUnbind()Method returnstrueIs executed, otherwise not.

If there is something wrong, please correct it

If you think it helps, give it a thumbs up!