I’m going to make a Service for Android

Thank you minmin little sister’s conclusion: www.jianshu.com/u/203b606b9…

Services are the Android solution for running applications in the background. They are ideal for performing tasks that require no interaction with the user and require a long run. Services are mainly responsible for non-UI-related tasks, such as time-consuming operations.

A: Service summary

(1) Start the child thread

(2) Asynchronous message processing mechanism

Two: Service cycle

Three: basic usage of Service

(1) Common Service

(2) Front desk Service

(3) System Service

Demo: background scheduled taskCopy the code

(4) the IntentService

Communication between services and activities

1 Service profile

A Service runs independent of any user interface, so it keeps running even if the program is switched to the background or the user opens another application. When an application process is killed, all services that depend on that process stop running.

Also note that a Service is one of the four components that does not run in a thread or a separate process; it executes in the UI thread. Therefore, time-consuming operations cannot be performed in a Service, and unless a child thread is opened manually, the main thread may be blocked. Which ANR.

(1) The most common way to start a Thread is to simply create a new Thread and implement the Runnable interface. By calling its start() method, you can perform time-consuming operations in the overridden run method. Example:

(2) Asynchronous message processing mechanism

One more note: Android does not allow UI manipulation in child threads. But sometimes, after executing some time-consuming tasks in the child thread, the UI control needs to be updated according to the execution result of the task. Here, Android provides a set of asynchronous message processing mechanism, which can well solve the problem of updating the UI in the child thread. Two main classes are used: Handler (a Handler, which is primarily used to send and process messages) and Message (a Message, which can carry a small amount of information for exchange between threads). The following figure shows how they can be used to convert child threads to main threads:

As you can see, if you instantiate a Message object and carry the data in the child thread that needs to be converted to the main thread for UI operations, Handle’s sendMessage() sends it out, This data is then received and processed by the override method handleMessage() of the Handle instantiated in the main thread. It is now easy to update the UI in child threads.

2.Service life cycle

The official documentation provides the Sevice lifecycle diagram as follows:

Let’s take a look at the meanings of these fallback methods:

OnCreate (): called when the service is first created

OnStartCommand () : called when the service starts

OnBind (): called when the service is bound

OnUnBind (): called when the service is unbound

OnDestroy (): called when the service stops

As you can see from the above journey, there are two ways to start a Service.

In the first case, other components call the StartService() method of the Context to start a Service and call back onStartCommand() from the Service. If the service has not been created before, the callback order is onCreate() -> onStartCommand(). Once started, the service remains running until the stopService() or stopSelf() method is called and the service stops with onDestroy() undone. In addition, no matter how many times you start calling the startService() method, you only need to call stopService() or stopService() once and the service will stop.

BindService (), which other components call the Context, can bind to a Service and call back the onBind() method in the Service. Similarly, if the service has not been created before then, the callback order is onCreate() -> onBind(). The calling method then gets an instance of the IBinder object returned from the onBind() method and communicates with the service. As long as the connection between the caller and the service is not broken, the service will continue to run until the unbindService() method is called, in the order onUnBind() -> onDestroy().

Tip: The two startup methods do not conflict. After starting a Service with startService(), you can also bind it with bindService(). You simply need to call both the stopService() and unbindService() methods for the service to be destroyed.

3 Basic usage of Service

Now that we’ve covered the Service life cycle and how to start it, let’s look at an example

(1) Common Service

First: Create a new class that inherits the Service and must override the onBind() method, optionally overriding onCreate(), onStartCommand(), and onDestroy().

Second: Register in the configuration file. In addition to broadcast, the four components of Android can use dynamic registration. Other defined components need to complete the registration step in the configuration file.

Third: Start a Service with an Intent in an activity. (Intent gives me the impression that anything can be launched,,)

Method for stopping Service:

Intent intent = new Intent(this, MyService.class);
stopService(intent);
Copy the code

Ok, let’s write an actual example, define a MyService, override the following four methods and print a single line of log.

See MainActivity

Don’t forget to sign up

See what happens when you click start

Results when you click Stop

2 at the front desk Service

The biggest difference between the foreground service and the common service is that the former always has a running icon displayed in the status bar of the system. When you pull down the status bar, you can see more detailed information, which is very similar to the effect of notification. Use front desk services either to prevent them from being recycled, such as listening to music, or for special needs, such as real-time weather conditions.

Implementing a foreground service is very simple. It is very similar to sending a Notification, except that after building a Notification, you do not need the NotificationManager to display the Notification. Instead, you call the startForeground() method.

Modify MyService’s onCreate() method

There was a problem with my testing here. It is on Android 8.1 that the system will report an error, which will directly cause the APP to restart. I tested it on my own real machine (8.0). Although there was no error, there was no foreground notification as EXPECTED. The exact reason for this is unclear, but I thought I’d Google it and see that someone on StackOverflow also mentioned this error. You need to create your own notification channel. You need to create a Notification channel.

This is the answer solution on StackOverflow. I ran fine display on 7.0

This is the result. Let’s look at the code

Modify the onCreate method in the Service. And of course it’s OK for you to use it in the onStartCommand method. I did a search on the Internet, and it looks like more people are using onStartCommand.

What system services are there besides the ones we open ourselves?

The corresponding service object is obtained by passing in a Name through the getSystemService() method.

Let’s now look at another system service, AlarmManager, to implement a background scheduled task. Calling AlarmManager’s set() method sets a scheduled task and provides three parameters (the job type, the time when the scheduled task is triggered, and the PendingIntent object). The three parameters are explained below.

(1) Job type: There are four values to choose from

(2) Time when the scheduled task is triggered: in milliseconds, the corresponding relationship between the passed value and the first parameter is:

PendingIntent object: The getBroadcast() method is called to retrieve a PendingIntent capable of performing a broadcast. This allows the broadcast receiver’s onReceive() method to be executed when the scheduled task is triggered.

Modify MyService, delete all the foreground service code, override onStartCommand(), get the instance of AlarmManager, and define the task to be triggered 10 seconds later. Use PendingIntent to specify the broadcast receiver that handles the scheduled task as MyReceiver, and then call set() to complete the setting.

Here we define a broadcast receiver called MyBroadcast(), which starts MyService with an Intent object in the onReceiver method. After this is done, the onReceive method broadcast 10 seconds later is executed and MyService is started, repeating the loop. This completes a service that can perform scheduled tasks in the background for a long time.

Don’t forget to sign up for the broadcast

In addition, since Android 4.4, the system has been optimized in terms of power consumption so that the Alarm task trigger time is not accurate. If the exact execution time of an Alarm task is required, replace the set() method with the setExact() method of AlarmManager.

To be honest, I think Little Sister Minmin is really good. I started to learn Android in my sophomore year, and I began to learn Android and do projects in detail in my junior year. However, I was not good enough in basic use. This time, I reviewed the summary materials of my sister and added many knowledge points that I had not noticed before.

(4) IntentServie

To make it easy to create an asynchronous, auto-stop service, Android provides an IntentService class. It is very similar to the use of a normal Service.

The first: Create a class that inherits IntentService, provide a parameterless constructor and call the parent’s parameterless constructor inside it, then implement the onHandleIntent() method, where you can handle time-consuming operations without worrying about ANR. Because the method itself is running in a child thread.

Second: you also need to register in the configuration.

Third: Start an IntentService in an activity with an Intent, exactly the same way you start a Service.

Don’t forget to register, register

The code in MainActivity

The result is as follows

There’s also a main thread

4. Communication between Service and Activity

This is the last part of the Service. If you want to communicate with an Activity, you need to use the service’s onBind() method. For example, if you want to provide a download function in MyService, you can decide when to start the download and view the download progress at any time in the activity.

First, use MyService to create a custom MyBinder class that extends with Binder and provides internal methods to start downloading and view the progress of downloading.

Second: Return the MyBinder class just defined in MyService’s onBind() method

The third: Instantiate a ServiceConnection class in the activity and override its onServiceConnection() and onServiceDisconnertion() methods, which are called when the activity and service are successfully bound and unbound, respectively. In the onServiceConnection() method, an instance of MyBinder is obtained by a downward transformation. You can then communicate with each other to call MyBinder’s methods.

Fourth: Prepare two more buttons in the activity layout for binding and unbinding services. Use Intent objects to bind and unbind activities and services in their click events. BindService () implements the binding, which takes three parameters (Intent object, ServiceConnection object, flag bit), passing BIND_AUTO_CREATE to indicate that the service is automatically created after the activity and service are bound. Unbind unbindService() and pass in the ServiceConnection object.

Let’s look at the results

You can see that both methods have been successfully called. Here is the knowledge summary and sharing of little sister Minmin.

May we be who we really are