In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to understand the principle of use from Service to WorkManager". The content in the article is simple and clear, and it is easy to learn and understand. please follow the editor's train of thought to study and learn "how to understand the principle of use from Service to WorkManager".
Concept and use
Service is an application component that can perform long-running operations in the background without providing an interface.
There are two ways to start:
The life cycle of startService () is: onCreate ()-> onStartCommand ()-> onDestory ()
The life cycle of bindService () is: onCreate ()-> onBind ()-> onUnBind ()-> onDestory ()
One thing to note is the return value of the onStartCommand method, which has three constants:
1) START_NOT_STICKY, after the service is terminated, the system will not rebuild the service unless the Intent is suspended to be passed.
2) START_STICKY, after the service is terminated, the service is automatically re-served and onStartCommand () is called, but the last Intent is not redelivered.
3) START_REDELIVER_INTENT, after the service is terminated, the service is rebuilt and onStartCommand () is called through the last Intent passed to the service.
Of course, if you want to use it finally, you have to register in the manifest file:
. . .
Service and child threads
With regard to Service, my first reaction is to run services in the background.
With regard to the background, my first reaction was again child threads.
So what exactly is the relationship between Service and child threads?
Service has two more important elements:
Run for a long time. Service can continue to run after the Activity is destroyed and the program is closed.
Application components that do not provide an interface. This actually explains the meaning of background, which means that Service does not interact with the interface and does not rely on UI elements.
And the key point is that Service also runs in the main thread.
So there is a big difference between Service running in the background and threads running in the background.
First, the threads running are different. Service is still running on the main thread, and the child thread must have opened up a new thread.
Secondly, the concept of backstage is different. The background of Service refers to not interacting with the interface, and the background of child threads refers to running asynchronously.
Finally, as one of the four major components, Service is more convenient to control, as long as there is a context to control it.
Of course, although the two concepts are different, there is still a lot of cooperation.
Service, as a component running in the background, is often used to do time-consuming operations, so the Service running on the main thread must not be able to do time-consuming operations directly, which requires child threads.
The combination of opening a background Service and performing subthreading operations in the Service is more likely to bring about the project.
It was with this in mind that Google designed IntentService, a component that has been combined for us to use.
IntentService
IntentService is a class that inherits from Service, comes with worker threads and Handler, and is automatically destroyed when the thread task ends.
The source code is simple:
@ Override public void onCreate () {super.onCreate (); / / create a new thread and start HandlerThread thread = new HandlerThread ("IntentService [" + mName + "]"); thread.start (); mServiceLooper = thread.getLooper (); / / create a new thread corresponding to handler mServiceHandler = new ServiceHandler (mServiceLooper) } @ Override public void onStart (@ Nullable Intent intent, int startId) {/ / service sends a message to handler Message msg = mServiceHandler.obtainMessage (); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage (msg);} private final class ServiceHandler extends Handler {public ServiceHandler (Looper looper) {super (looper) } @ Override public void handleMessage (Message msg) {/ / handler calls the onHandleIntent method onHandleIntent ((Intent) msg.obj); stopSelf (msg.arg1);}} after receiving the message
Malpractice
As mentioned earlier, these features of Service do give us more possibilities, we can silently download what the project needs, can be heartbeat, and can deal with some data.
However, it is precisely because of the non-perception in the background that it also brings hidden dangers and drawbacks in terms of privacy.
App can manipulate user data in the background, download application-independent files, and so on.
So in order to protect the privacy of users, Google limits the background Service at the beginning of Android8.0.
Background and foreground Service
This involves the classification of Service.
Service can be divided into foreground and background if it is classified according to whether it is unaware or not. The foreground Service will let users feel that there is such a thing running in the background by way of notification.
For example, music APP, while playing music in the background, you can find that there is always a notice displayed in the foreground to let users know that there is such a music-related service in the background.
In Android8.0,Google, if the program is in the background, then the background service cannot be created, and the background service that has been opened will be stopped after a certain period of time.
Therefore, it is recommended to use the foreground Service, which has a higher priority and is not easy to destroy. The method of use is as follows:
StartForegroundService (intent); public void onCreate () {super.onCreate (); Notification notification = new Notification.Builder (this) .setChannelId (CHANNEL_ID) .setContentTitle ("main service") / / title .setContentText ("running...") / / content .setSmallIcon (R.mipmap.ic_launcher) .build (); startForeground (1Magna notification) }
What about the backstage mission? The official recommendation is to use JobScheduler.
JobScheduler
Task scheduling JobScheduler,Android5.0 is launched. (some friends may feel strange, but in fact, he also realized it through Service. We'll talk about this later.)
What it can do is to perform tasks automatically according to your requirements. For example, when the time is specified, when the network is WIFI, when the equipment is idle, when charging, etc., the background automatically runs.
So Google uses it to replace some of the functions of background Service, using:
First, create a JobService:
Public class MyJobService extends JobService {@ Override public boolean onStartJob (JobParameters params) {return false;} @ Override public boolean onStopJob (JobParameters params) {return false;}}
Then, register for the service (because JobService is also Service)
Finally, create a JobInfo and execute
JobScheduler scheduler = (JobScheduler) getSystemService (Context.JOB_SCHEDULER_SERVICE); ComponentName jobService = new ComponentName (this, MyJobService.class) JobInfo jobInfo = new JobInfo.Builder (ID, jobService) .setMinimumLatency (5000) / / minimum delay time for the task. SetOverrideDeadline (60000) / / Task deadline. The .setRequiredNetworkType (JobInfo.NETWORK_TYPE_UNMETERED) / / network condition will be executed when the specified condition is not met. The default value is NETWORK_TYPE_NONE .setRequiresCharging (true) / / whether to charge. SetRequiresDeviceIdle (false) / / whether the device is idle. SetPersisted (true) / / whether to continue execution after the device is rebooted. SetBackoffCriteria (3000 JobInfo. BACKOFFORPOLINEAR) / set Backoff / retry policy .build () Scheduler.schedule (jobInfo)
Briefly describe the principle:
JobSchedulerService is a service started in SystemServer, and then traverses the outstanding tasks, finds the corresponding JobService through Binder, executes the onStartJob method, and completes the task. Specifically, you can take a look at the analysis of the reference link.
So we know that after 5. 0, you can use JobScheduler if you need to perform background tasks, especially those that need to be triggered by certain conditions, such as network power, and so on.
Some people may ask, what should we do before 5.0?
You can use GcmNetworkManager or BroadcastReceiver to handle some of the task requirements.
Google also takes this into account, so it combines the post-5.0s JobScheduler and the pre-5.0s GcmNetworkManager, GcmNetworkManager, AlarmManager and other task-related API to design WorkManager.
WorkManager
WorkManager is an API that allows you to easily schedule deferred asynchronous tasks that should run even after exiting the application or restarting the device.
As a member of Jetpack, it is not very new. Its essence is to combine the existing API related to task scheduling, and then perform these tasks according to version requirements. There is a picture on the official website:
So what exactly can WorkManager do?
1. Some task constraints can be well executed, such as the tasks that need to be performed under the conditions of network, idle state of equipment, sufficient storage space, etc.
2, can repeat, one-time, stable execution of the task. Can continue the task, including after the device is restarted.
3. The cohesion of different tasks can be defined. For example, set one task after another.
In short, it is a powerful tool for performing tasks in the background.
Thank you for your reading, the above is the content of "how to understand the principle of use from Service to WorkManager". After the study of this article, I believe you have a deeper understanding of how to understand the principle of use from Service to WorkManager. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.