通過調用startForeground
使您的Service
在前臺運行將向系統發出信號,告知系統查殺和/或垃圾回收服務會對用戶造成干擾。這將阻止系統清理您的服務,除非由於系統資源較低或功耗較低而無法完成。
要使Service
在前臺運行,您需要給它一個Notification
。這是可以做到像這樣:
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.notification_icon);
builder.setContentTitle("Your notification text");
builder.setProgress(100, 0, true); /* 0 out of 100 progress to start */
builder.setAutoCancel(false);
builder.setOngoing(true);
Notification notification = builder.getNotification();
/* NOTIFICATION_ID can just be a static int to identify your service's notification */
startForeground(NOTIFICATION_ID, notification);
這是使用startForeground的一個非常基本的例子,但至少應該讓你在正確的方向。當您的操作完成後,您可以通過致電stopForeground
向系統發信號通知您可以自由收集。
我建議看一下['IntentService'](http://developer.android.com/reference/android/app/IntentService.html)或者讓你的'Service' [在前臺運行](http:/ /developer.android.com/reference/android/app/Service.html#startForeground)和'Notification'。 – MCeley 2013-03-22 19:14:59
由於潛在的併發問題,我實際上不能使用IntentService。我希望將這項服務用於幾種不同的事情,不僅僅是上傳和下載,而且我還需要其中一些操作來阻止彼此。發送到IntentServices的操作將始終按照我的理解連續運行?如果沒有,那麼這看起來是正確的解決方案。 – akhalsa 2013-03-22 19:18:20
我對應用的後臺進程有混合服務。它充當'IntentService'來調度某些數據同步操作,但它可以被綁定到檢索進度更新。我允許該服務在後臺繼續下載,但我故意沒有執行。我的理解是,要防止服務被踢出去,您需要獲得前臺通知。 – 323go 2013-03-22 19:19:58