最近在使用android 4.1系統的時候,發現在手機休眠一段時間後(1-2小時),後台啟動並執行服務被強行kill掉,有可能是系統回收記憶體的一種機制,要想避免這種情況可以通過startForeground讓服務前台運行,當stopservice的時候通過stopForeground去掉。
以下是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 should 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, call startForeground().
This method takes two parameters: an integer that 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, 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 about how to provide backward compatibility.
For more information about notifications, see Creating Status Bar Notifications.
要想實現需求,我們只需要在onStartCommand裡面調用 startForeground,然後再onDestroy裡面調用stopForeground即可!
實際情況就譬如手機裡面的音樂播放器一樣,不管手機如何休眠,只要開始播放音樂了,就不會kill掉這個服務,一旦停止播放音樂,服務就可能被清掉。
FYI