Foreground Service

當app有背景service在運行時, 可以利用foreground service的特性來提醒使用者目前有正在運行的背景服務,
這種方式也可以讓系統在記憶體不足時不會先被系統給砍掉

(先被砍掉的通常是那些看不到的背景服務)

要讓service變成Foreground Service的方法很簡單
只要在service動時, 發一個notification, 並且呼叫startForeground() method就可以了

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_ID, notification);

如果要停止的話也只要呼叫stopForeground() method

如果可以獲得系統權限的話, 也可以在AndroidManifest.xml的application增加

android:persistent="true"

如此一來也可以盡可能避免service被系統砍掉囉