preface

  • learnAndroidFor a period of time, many people must be the same as me, at ordinary times often learn the east west gather together, feel knowledge point some messy difficult system. So I am taking advantage of my spare time in these few days to summarize what I have learned and stroke my mind.

This article mainly aims at Service related knowledge points, carries on the detailed combing, wishes everybody eats happily!

The article directories

For your convenience, I’m hereGitHubSet up a warehouse


  • The warehouse content is updated synchronously with the blog. Due to my rare earth mining brief book CSDN blog park and other sites, there are new content published. So you can directly follow the warehouse, so as not to miss the highlights!

  • Warehouse address: Super dry goods! Carefully summarized Android, JVM, algorithm, etc., you handsome old iron support! For a Star!

What is a Service


1.1 What is Service

  • ServiceA service is an application component that runs operations in the background for a long time without a user interface.
  • Services can be started by other application components (e.gActivityOnce started, the service runs in the background, even if the component that started the service (Activity) has been destroyed is not affected.
  • In addition, components can be bound to services to interact with 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 rely on the user visible UI interface (although this is not absolute, for example, the foreground Service is used in conjunction with the Notification interface)

  2. Has a long time running characteristics

  3. Note: is running in the main thread

1.3 Service Process

  • A service process is a process started by the startService() method, but is not a foreground and 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.

Chapter two: Life Cycle


2.1 Service Life Cycle

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

2.2 Two Ways to Enable the Service

2.2.1 startService ()

  1. Define a class that inherits Service

  2. Configure the Service in the manifest.xml file

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

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

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

2.2.2 bindService ()

  1. Create a BindService server that inherits the Service and, in the class, creates an instance object that implements the IBinder interface and provides a public method for the Activity to call.

  2. Returns the Binder instance from the onBinder() callback method.

  3. Binder objects are received from the onServiceConnection() callback argument in the Activity client to access data inside the Service.

  4. Use the BindService () method to start the BindService and unbind the BindService () method in its sse use.

  5. This startup depends on the client lifecycle. When the client Activity is destroyed, the Service stops destroying without calling the unbindService() method.

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 throughonCreateonStart, and then in the running state,stopServiceIs called whenonDestroyMethods.

If the caller simply exits without calling stopService, the Service will always run in the background.

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.

The so-called bound together to live or die together. The caller can also stop the service by calling the unbindService method, in which case Srevice calls onUnbind -> onDestroyed.

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

  1. 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.

  2. 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.

  3. 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

  4. 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.

  5. 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

3.1.1 The first point is defined

  1. threadIs the smallest unit of program execution, it is allocationcpuIn Android, what we call the main thread,UIThread is a kind of thread. Of course, threads can also perform time-consuming asynchronous operations.
  2. whileserviceRemember, it’s a special mechanism in Android,serviceIs running in the main thread, so it can’t do time-consuming operations, it’s hosted by the system process, actuallyserviceIt’s also a lightweightIPCCommunication, becauseactivityYou can andserviceBind, can andserviceData communication.
  3. And there’s a situation where,activityserviceAre in different processes, so the data communication between them has to go throughIPCInterprocess communication mechanism to operate.

3.1.2 The second point is in the actual development process

  1. In Android, a thread is usually a worker thread, a background thread, a thread that does something time-consuming, and the main thread is a special thread that just handles somethingUIThread drawing,UIThe most basic and important point is that you should never do time-consuming operations in a thread. (this isThreadApplication in the actual development process)
  2. whileserviceIt’s one of the four main components in Android, and it runs in the main thread, soserviceDo not perform time-consuming operations. Otherwise, the system will report an ANR exception (ANRFull name:Application Not Responding), the program cannot respond.
  3. If you have to be thereserviceMake sure to open a separate thread for time-consuming operations.

3.1.3 The third point is application scenarios

  1. When you need to perform time-consuming network, or this kind of file data query, and other blockingUIWhen using threads, you should always use worker threads, which is the way you start a child thread.
  2. So that we can be sureUIThreads are not occupied and the user experience is affected.
  3. whileserviceFor example, we often need to run in the background for a long time and do not need to interact with each other before we can use the service. For example, we play music in the background, start the statistics of weather forecast and some data statistics.

3.2 Why Service instead of Thread

  • ThreadThe operation is independent ofActivityIs to be aActivityfinishAnd then if you don’t stopThreadorThreadIn therunUntil it’s done, this thread is going to keep executing.
  • So here’s a problem: whenActivityfinishAfter that, you no longer hold theThreadThe reference.
  • On the other hand, you have no way in differentActivityIn the sameThreadControl.

3.3 Can Time-consuming Operations be Performed in the Service

  • Service cannot perform time-consuming operations (network requests, copying databases, large files)

  • A Service 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 to write time-consuming logic and operations (e.g., network requests, copying databases, large files) in a Service most of the time, otherwise it will cause ANR.

  • If you want to perform time-consuming tasks in a service. There are the following solutions:

  1. inserviceTo start a child thread
new Thread(){}.start();
Copy the code
  1. You can useIntentServiceManage services asynchronously (aboutIntentServiceThe content is given below.)

3.4 Check whether the Service is executed on the main Thread

  • By default, if no indication is indicatedserviceThe process being run,ServiceactivityIs running in the presentappOf the process in whichmain thread ( UIMain thread) inside.
  • ServiceActivityOn the same thread, for the sameappIs in the same thread by defaultmain Thread ( UI Thread )
  • Special cases can be configured in the manifest fileserviceExecute the process in which you are runningserviceExecute in another processServiceimmortality

Note: If Thread is created in application: The life cycle of this Thread is the same as the life cycle of the app. Different activities can also operate it. In this case, the service and the Thread are similar (provided that the service is only available for its own app and cannot be accessed by third-party apps).

3.4.1 track inonStartCommandmethodflagSet toSTART_STICKY ;

<service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" >
</service>
Copy the code
return Service.START_STICKY;
Copy the code

3.4.2 is set in XMLandroid:priority

<! -- Set service priority to MAX_VALUE-->
 <service android:name=".MyService"
          android:priority="2147483647"
          >
 </service>
Copy the code

Rule 3.4.3 inonStartCommandMethod as the foreground process

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  Notification notification = new Notification(R.mipmap.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

3.4.4 inonDestroyRestart in methodservice

@Override
public void onDestroy(a) {
    super.onDestroy();
    startService(new Intent(this, MyService.class));
}
Copy the code

3.4.5 withAlarmManager. SetRepeating (...).Method circulates the alarm broadcast and is called when it is receivedserviceonstartmethods

Intent intent = new Intent(MainActivity.this,MyAlarmReciver.class);
PendingIntent sender = PendingIntent.getBroadcast( MainActivity.this.0, intent, 0);

// We want the alarm to go off 10 seconds from now.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 1);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
// Repeat the alarm
/ * * *@param type
 * @paramTriggerAtMillis t The first execution of an alarm in milliseconds * Go off, using the appropriate clock (depending on the alarm type). *@paramIntervalMillis indicates the interval between alarm execution, also in milliseconds * of the alarm. *@paramOperation binds the alarm's execution actions, such as sending a broadcast, giving a hint, and so on */
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 2 * 1000, sender);
Copy the code

3.4.6 Message push of many three parties in the current marketSDKWake up theAPP, e.g.Jpush

PS: These methods do not mean that your Service is immortal, only that they increase the priority of the process. So far I haven’t found a way to get rogue requests through the usual methods (not even by long pressing the home button to clear them), but all the current methods are ways to keep running through Android’s memory reclamation mechanism and common third-party memory cleansing, etc. Some phone manufacturers have whitelisted these well-known apps to improve user experience by keeping the process immortal (wechat, QQ and Momo are all on Xiaomi’s whitelist). If they are removed from the whitelist, they will eventually be killed just like ordinary apps.

IntentService


  • As an old driver, if evenInterserviceI never heard of it, so that’s kind of what it is

4.1 What is IntentService

  • IntentService is a subclass of Service that adds additional functionality over regular Service.

  • There are two problems with our common services:

  1. A Service does not start a single process; it is in the same process as the application in which it resides

  2. A Service is also not dedicated to a new thread, so time-consuming tasks should not be handled directly within a Service

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

  1. When an application is hung in the background, it is introduced to ensure that certain components of the application are still workingServiceThe concept of
  2. So here’s what I want to emphasize: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 that would otherwise causeANR

That is, no time-consuming operations can be performed in a service. Although in the background service. But it’s also inside the main thread.

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

  1. IntentServiceIs inheritedServicePhi, then it contains phiServiceThe full range of features, of courseserviceLife cycle of.
  2. Then theserviceThe difference is,IntentServiceIn the implementationonCreateWhen operating, an internal thread is opened for you to perform your time-consuming operation.

4.3.3 use:

  1. rewriteprotected abstract void onHandleIntent(Intent intent)

4.3.4 IntentServiceIs a pass throughContext.startService(Intent)A startup that can handle asynchronous requestsService

  1. When you use it, you just inheritIntentServiceAnd rewrite thatonHandleIntent(Intent)Method receives aIntentThe object stops itself at the appropriate time (usually when the work is done).
  2. 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

  1. Each time you start the service, instead of doing your work immediately, you create the correspondingLooperHandlerAnd in theMessageQueueAdded in the attached customerIntentMessageObject.
  2. whenLooperFound to haveMessageAnd then you getIntentObject passes throughonHandleIntent((Intent)msg.obj)Call your handler and stop your service when it’s done.
  3. meanIntentThe lifecycle of the service is consistent with the task you are working on, 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:

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

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

  3. 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

  1. ServerThe terminal sends the current download progress through broadcasting.ClientThe end registers the listener of this broadcast. After obtaining the broadcast, the current download progress in the broadcast is resolved and updated to the interface.
  2. Define your own broadcast, so in differentActivityServiceAnd applications can interact with each other through broadcasting.

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 toAndroidIPCMechanism, commonly used for cross-process communication, based on the underlying implementation principleBinderMechanism.
  • Android interview, interaction with Service

Chapter six: Use


6.1 When is Service used

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

  1. According to theServiceWe can know the work that needs to be done in the background for a long time and we need to put it inServiceIn to do it.
  2. It needs to be a little more comprehensible, but it can’t beActivityTo perform the work must be placed inServiceIn to do it.
  3. For example, play music, download, upload large files, and close applications periodically. These functions if you put them inActivityIf you do, thenActivityIf the exit is destroyed, then these functions are stopped, which is obviously not in accordance with our design requirements, so we put them inServiceTo execute.

6.2 onStartCommand() Return Value Int Value difference

  • There are four return values, each representing the following:

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.

  • inonDestroyMethod in the broadcast restartservice
  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.

conclusion


  1. This article basically covers itAndroid ServiceRelated knowledge points. Due to the lack of space, there is no way to give a detailed introduction to the specific use methods of InterService. It is easy to find materials on the Internet for learning.
  2. Focus on: aboutAndroidSo far, I have summarized the four major componentsActivityServiceI will continue to target,BroadcastRecevier ContentProviderAnd other important modules besides the four components, such as event distribution, sliding conflict, new energy optimization, etc., are comprehensively summarized. Welcome your attentionThe nuggets of _yuanhaoTo receive updates in a timely manner
  3. Before the beginning also thought that the summary is not difficult, in the actual process of writing the article, just know what is hard. I don’t know if I can stick to it. I hope you can encourage me. Even if it’s just a compliment, it’s also the reason why I stick to it!

Code word is not easy, your praise is my summary of the biggest power!


  • Due to my “rare earth nuggets”, “Jian Shu”, “CSDN”, “Blog park” and other sites, there are new content released. So you can directly follow my GitHub repository, so as not to miss the great content!

  • Warehouse address: Super dry goods! Carefully summarized Android, JVM, algorithm, etc., you handsome old iron support! For a Star!

  • 1W words long article, plus exquisite mind map, remember to like oh, welcome to pay attention to the gold digging _Yuanhao

  • Related articles can be seen on my home page, GitHub, here is limited to space reasons, but also to keep the interface clean, so that you can have a comfortable reading experience will not be given, our next article will be there!