preface
- learn
Android
For 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
Service
A 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.g
Activity
Once 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 visible
UI
interface - So, in terms of actual business requirements,
Service
Applicable scenarios should meet the following conditions:
-
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)
-
Has a long time running characteristics
-
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 first
Service
The basic flow of the life cycle - A famous picture
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 ()
-
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.
-
Returns the Binder instance from the onBinder() callback method.
-
Binder objects are received from the onServiceConnection() callback argument in the Activity client to access data inside the Service.
-
Use the BindService () method to start the BindService and unbind the BindService () method in its sse use.
-
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
Service
Go throughonCreate
到onStart
, and then in the running state,stopService
Is called whenonDestroy
Methods.
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?
-
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
3.1.1 The first point is defined
thread
Is the smallest unit of program execution, it is allocationcpu
In Android, what we call the main thread,UI
Thread is a kind of thread. Of course, threads can also perform time-consuming asynchronous operations.- while
service
Remember, it’s a special mechanism in Android,service
Is running in the main thread, so it can’t do time-consuming operations, it’s hosted by the system process, actuallyservice
It’s also a lightweightIPC
Communication, becauseactivity
You can andservice
Bind, can andservice
Data communication. - And there’s a situation where,
activity
和service
Are in different processes, so the data communication between them has to go throughIPC
Interprocess communication mechanism to operate.
3.1.2 The second point is in the actual development process
- 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 something
UI
Thread drawing,UI
The most basic and important point is that you should never do time-consuming operations in a thread. (this isThread
Application in the actual development process) - while
service
It’s one of the four main components in Android, and it runs in the main thread, soservice
Do not perform time-consuming operations. Otherwise, the system will report an ANR exception (ANR
Full name:Application Not Responding
), the program cannot respond. - If you have to be there
service
Make sure to open a separate thread for time-consuming operations.
3.1.3 The third point is application scenarios
- When you need to perform time-consuming network, or this kind of file data query, and other blocking
UI
When using threads, you should always use worker threads, which is the way you start a child thread. - So that we can be sure
UI
Threads are not occupied and the user experience is affected. - while
service
For 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
Thread
The operation is independent ofActivity
Is to be aActivity
被finish
And then if you don’t stopThread
orThread
In therun
Until it’s done, this thread is going to keep executing.- So here’s a problem: when
Activity
被finish
After that, you no longer hold theThread
The reference. - On the other hand, you have no way in different
Activity
In the sameThread
Control.
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:
- in
service
To start a child thread
new Thread(){}.start();
Copy the code
- You can use
IntentService
Manage services asynchronously (aboutIntentService
The content is given below.)
3.4 Check whether the Service is executed on the main Thread
- By default, if no indication is indicated
service
The process being run,Service
和activity
Is running in the presentapp
Of the process in whichmain thread
(UI
Main thread) inside. Service
和Activity
On the same thread, for the sameapp
Is in the same thread by defaultmain Thread
(UI Thread
)- Special cases can be configured in the manifest file
service
Execute the process in which you are runningservice
Execute in another processService
immortality
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 inonStartCommand
methodflag
Set 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 inonStartCommand
Method 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 inonDestroy
Restart 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 receivedservice
的 onstart
methods
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 marketSDK
Wake 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 even
Interservice
I 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:
-
A Service does not start a single process; it is in the same process as the application in which it resides
-
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 Service
It is used for background services
- When an application is hung in the background, it is introduced to ensure that certain components of the application are still working
Service
The concept of - So here’s what I want to emphasize:
Service
It 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 casesService
Write 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 beservice
To manage, you need to introduceIntentService
。
IntentService
Is inheritedService
Phi, then it contains phiService
The full range of features, of courseservice
Life cycle of.- Then the
service
The difference is,IntentService
In the implementationonCreate
When operating, an internal thread is opened for you to perform your time-consuming operation.
4.3.3 use:
- rewrite
protected abstract void onHandleIntent(Intent intent)
4.3.4 IntentService
Is a pass throughContext.startService(Intent)
A startup that can handle asynchronous requestsService
- When you use it, you just inherit
IntentService
And rewrite thatonHandleIntent(Intent)
Method receives aIntent
The object stops itself at the appropriate time (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 work immediately, you create the corresponding
Looper
,Handler
And in theMessageQueue
Added in the attached customerIntent
的Message
Object. - when
Looper
Found to haveMessage
And then you getIntent
Object passes throughonHandleIntent((Intent)msg.obj)
Call your handler and stop your service when it’s done. - mean
Intent
The 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 summaryIntentService
The 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 one
Context
Context, whileService
Itself isContext
A subclass of - So in
Service
It’s totally okay to pop toast in there. Like when we were inService
After completing the download task, you can play a toast to notify the user.
5.5 Interaction mode with Service
5.5.1 Broadcast Interaction
Server
The terminal sends the current download progress through broadcasting.Client
The 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.- Define your own broadcast, so in different
Activity
、Service
And applications can interact with each other through broadcasting.
5.5.2 File Sharing Interaction
- We use the
SharedPreferences
To implement sharing, of course, you can use otherIO
In 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. Server
The end will write the current download progress into the shared file,Client
The end reads the download progress in the shared file and updates it to the main interface.
5.5.3 Messenger
Interaction (Messenger interaction)
Messenger
The translation refers to the messenger, and it quotes oneHandler
Object to which others can send messages (usingmMessenger.send ( Message msg )
Methods).- This class allows cross-process based
Message
Communication, used on the server sideHandler
To create aMessenger
The client just needs to get the serverMessenger
The object can then communicate with the server - in
Server
The terminal and the Client pass oneMessenger
Object, which acts as a sort of information relay through which all information is carried
5.5.4 Customizing Interface Interaction
- We do it ourselves through the implementation of the interface
Activity
与Service
The purpose of the interaction is through theActivity
和Service
Build a bridge between, so as to achieve the purpose of data interaction, and this kind of implementation andAIDL
Very similar - Customize an interface that has an empty method to get the current download progress.
Server
The end uses a class inherited fromBinder
And implement the interface, overwrite the method of obtaining the current download progress.Client
End byServiceConnection
Get 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 AIDL
interaction
- Remote services generally pass
AIDL
To implement, can carry out inter-process communication, this service is also called remote service. AIDL
Belong toAndroid
的IPC
Mechanism, commonly used for cross-process communication, based on the underlying implementation principleBinder
Mechanism.
- Android interview, interaction with Service
Chapter six: Use
6.1 When is Service used
6.1.1 Experience Summary:
Service
You know, doing things behind your back, and you don’t want anyone to know- For example, if you want to know something, you don’t need to ask directly, you can know it from the side. This is the
Service
Original intention of design
6.1.2 Service
Why was it designed
- According to the
Service
We can know the work that needs to be done in the background for a long time and we need to put it inService
In to do it. - It needs to be a little more comprehensible, but it can’t be
Activity
To perform the work must be placed inService
In to do it. - For example, play music, download, upload large files, and close applications periodically. These functions if you put them in
Activity
If you do, thenActivity
If the exit is destroyed, then these functions are stopped, which is obviously not in accordance with our design requirements, so we put them inService
To execute.
6.2 onStartCommand() Return Value Int Value difference
- There are four return values, each representing the following:
6.2.1 START_STICKY
:
- if
service
The process was killed and saved. Procedureservice
Is in the start state, but does not reserve the delivered stateintent
Object. - The system then attempts to recreate it
service
Because the service is in the start state, it must be invoked after the service is createdonStartCommand ( Intent, int, int )
Methods. - If no start command is passed to during this period
service
, then parametersIntent
Will provide thenull
。
6.2.2 START_NOT_STICKY
:
- “Non-sticky.”
- When using this return value, if the execution is done
onStartCommand
The service is abnormalkill
If no, the system does not restart the service automatically.
6.2.3 START_REDELIVER_INTENT
:
- The retransmission
Intent
。 - When using this return value, if the execution is done
onStartCommand
The service is killed by an exception - The system automatically restarts the service and passes in the Intent value.
6.2.4 START_STICKY_COMPATIBILITY
:
START_STICKY
Compatible version, but does not guarantee that the service iskill
We’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 to
Service
To perform network operations - in
onStartCommand()
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.
- in
onDestroy
Method in the broadcast restartservice
。
service
+broadcast
The way is whenservice
走ondestory
Sends a custom broadcast- When a broadcast is received, restart
service
. (Third-party apps or insetting
Li – When applying force stop,APP
The process just gets killed,onDestroy
Methods cannot be entered, so there is no guarantee that they will be executed.
- Listening system broadcast judgment
Service
State.
- Some broadcasts through the system
- For example: mobile phone restart, interface wake up, application state change, etc., monitor and capture, and then judge our
Service
Whether they’re still alive.
Application
addPersistent
Properties.
6.5 When is the onRebind (Intent) method of a Service Executed
- If the
onUnbind()
Method returnstrue
Is executed, otherwise not.
conclusion
- This article basically covers it
Android Service
Related 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. Focus on
: aboutAndroid
So far, I have summarized the four major componentsActivity
和Service
I will continue to target,BroadcastRecevier
ContentProvider
And 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- 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!