Recently in the use of Android 4.1 system, found that after a period of sleep (1-2 hours), the background service is forced to kill, it is possible that the system is a mechanism to reclaim memory, to avoid this can be done through the startforeground to let the service foreground run, When StopService is removed by Stopforeground.
Here is the official Android description:
Running a Service in the Foreground
A foreground service is a service that's considered to being something the user is actively aware of and thus not a candidate For the system to kill, low on memory. A foreground service must provide a notification for the status bar, which is placed under the "ongoing" heading, which me Ans That the notification cannot was dismissed unless the service is either stopped or removed from the foreground.
For example, a music player this plays music from a service should being set to run in the foreground, because the user is ex Plicitly aware of its operation. The notification in the status bar might indicate the "current song" and "Allow the" user to launch a activity to interact WI Th the music player.
To request this your service run in the foreground, call Startforeground (). This method takes the Parameters:an integer, uniquely identifies the notification and the notification for the status Bar. For example:
Notification Notification = new Notification (R.drawable.icon, GetText (R.string.ticker_text),
System.currenttimemillis ());
Intent notificationintent = new Intent (this, exampleactivity.class);
Pendingintent pendingintent = pendingintent.getactivity (this, 0, notificationintent, 0);
Notification.setlatesteventinfo (This, GetText (R.string.notification_title),
GetText (r.string.notification_message), pendingintent);
Startforeground (Ongoing_notification, NOTIFICATION);
To remove the service from the foreground, call Stopforeground (). This method takes a Boolean, indicating whether to remove the status bar notification as well. This method does not stop the service. However, if you stop the service while it's still running in the foreground and then the notification is also removed.
Note:the methods Startforeground () and Stopforeground () were introduced in Android 2.0 (API level 5). In order to run your service in the foreground on older versions of the platform, you must use the Previoussetforeground () Method-see the Startforeground () documentation for information on how to provide backward compatibility.
For more information about notifications, see Creating Status Bar notifications.
To achieve the requirements, we only need to call Startforeground inside the Onstartcommand, and then OnDestroy inside call Stopforeground!
The actual situation is like the music player in the mobile phone, no matter how the phone hibernate, as long as the music started to play, it will not kill the service, once stopped playing music, the service may be cleared away.
Use Startforeground to run the Android service foreground