Recently, when using the android 4.1 system, it was found that services running in the background were forcibly killed after the mobile phone sleep for a period of time (1-2 hours, there may be a mechanism for the system to recycle memory. To avoid this situation, you can use startforeground to run the service on the frontend. When stopservice is used, you can use stopforeground to remove it.
The following is an official description of Android:
Running a service in the foreground
A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. a foreground service must provide a notification for the status bar, which is placed under
The "ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.
For example, a music player that plays music from a service shocould be set to run in the foreground, because the user is explicitly aware of its operation. the notification in the status bar might indicate the current song and allow the user to launch an activity
To interact with the music player.
To request that your service run in the foreground, callstartForeground().
This method takes two parameters: an integer that uniquely identifies the notification andNotificationFor
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, callstopForeground().
This method takes a Boolean, indicating whether to remove the status bar notification as well. This method doesNotStop the service. However, if you stop the service while it's still running in the foreground, then the notification is also removed.
Note:The methodsstartForeground()AndstopForeground()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
ThestartForeground()Documentation
For information about how to provide backward compatibility.
For more information about notifications, see creating status bar notifications.
To implement the requirement, we only need to call startforeground in onstartcommand, and then call stopforeground in ondestroy!
The actual situation is like the music player in a mobile phone. No matter how sleep the mobile phone is, as long as you start playing the music, you will not kill the service. Once you stop playing the music, the Service may be cleared.
FYI