使用startForeground讓android服務前臺運行

最近在使用android 4.1系統的時候,發如今手機休眠一段時間後(1-2小時),後臺運行的服務被強行kill掉,有多是系統回收內存的一種機制,要想避免這種狀況能夠經過startForeground讓服務前臺運行,當stopservice的時候經過stopForeground去掉。android

如下是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.less

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.ide

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:this

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);orm

 

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.ci

For more information about notifications, see Creating Status Bar Notifications.rem

要想實現需求,咱們只須要在onStartCommand裏面調用 startForeground,而後再onDestroy裏面調用stopForeground便可!
實際狀況就譬如手機裏面的音樂播放器同樣,無論手機如何休眠,只要開始播放音樂了,就不會kill掉這個服務,一旦中止播放音樂,服務就可能被清掉。get

相關文章
相關標籤/搜索