9.5.1 use of the front desk service
Services are almost always running in the background, it has been silently doing a hard work. However, the system priority of the service is still relatively low, and when the system is out of memory, it is possible to reclaim services that are running in the background. If you want the service to remain running and not be recycled due to low system memory, consider using the foreground service. Front desk service and normal service The biggest difference is that it will always have a running icon in the System status bar display, drop-down status bar can see more detailed information, very similar to the effect of notification. Of course, sometimes you may not only to prevent the service from being recycled to use the front desk service, some items due to special requirements will require the use of front desk services, such as ink weather, its service in the background to update the weather data, but also in the system status bar has been displayed the current weather information, 9.11 is shown.
Figure 9.11
So let's take a look at how we can create a front-desk service, which is actually not complicated, modify the code in MyService as follows:
public class MyService extends Service {
......
@Override
public void OnCreate () {
Super.oncreate ();
Notification Notification = new Notification (R.drawable.ic_launcher, "Notification Comes", System. Currenttimemillis () );
Intent notificationintent = new Intent (this, mainactivity.class);
Pendingintent pendingintent = pendingintent.getactivity (this, 0, notificationintent, 0);
Notification.setlatesteventinfo (This, "This is the title", "This is content", pendingintent);
Startforeground (1, notification);
LOG.D ("MyService", "OnCreate executed");
}
......
}
As you can see, this just modifies the code in the OnCreate () method, believing that this part of the code will look familiar to you. That's right! This is the method of creating notifications that we learned in the previous chapter. It is only this time that the Notification object has been built without using Notificationmanager to display the notification, but instead calls the Startforeground () method. This method receives two parameters, the first parameter is the ID of the notification, similar to the first argument of the Notify () method, and the second parameter is the Notification object that is built. Calling the Startforeground () method causes MyService to become a foreground service and is displayed in the System status bar.
Now rerun the program and click on the start service or the Bind service button, MyService will start in front of the service mode, and in the System status bar will display a notification icon, drop down status bar can see the details of the notification, 9.12.
Figure 9.12
Android: Using the front desk service