2013-06-30 80 views
8

我已經創建了一個服務(EmailService)發送電子郵件...每次我需要發送一封電子郵件與我的應用程序,它啓動服務並通過意圖傳遞電子郵件的ID ...多次調用startforeground?

我我正在使用startforeground(id_of_email, mynotifcation);來防止它被殺,並向用戶顯示發送電子郵件狀態的通知。

我需要讓用戶在時間發送多封電子郵件,因此當用戶需要發送另一封電子郵件,它再次調用startservice一個新的意圖(不同的ID電子郵件)...所以它再次調用startforeground(new_id_of_email, mynotifcation);

的問題是,要startforeground新的呼叫覆蓋以前的通知......(這樣用戶失去了先前的通知,不知道是怎麼回事,他以前的電子郵件)

+0

不是將數據庫中的任務排隊或更好嗎?這樣,一旦第一次完成,服務會更新它,完成或刪除它並檢查是否還有其他事情要做。也許一個消息隊列繼續爲更多的任務提供服務 – eduyayo

回答

2

縱觀Service.startForeground()源顯示多次調用startForeground只會替換當前顯示的通知。實際上,對startForeground的調用與stopForeground()相同,只有removeNotification設置始終設置爲true。

如果您希望爲您的服務顯示正在進行的每封電子郵件的通知,則必須單獨管理服務中的每個通知。

public final void startForeground(int id, Notification notification) { 
    try { 
     mActivityManager.setServiceForeground(
       new ComponentName(this, mClassName), mToken, id, 
       notification, true); 
    } catch (RemoteException ex) { 
    } 
} 

public final void stopForeground(boolean removeNotification) { 
    try { 
     mActivityManager.setServiceForeground(
       new ComponentName(this, mClassName), mToken, 0, 
       null, removeNotification); 
    } catch (RemoteException ex) { 
    } 
} 

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r1/android/app/Service.java#Service.startForeground%28int%2Candroid.app.Notification%29

0

一方面也可以使用STOP_FOREGROUND_DETACH標誌。

documentation引用:

STOP_FOREGROUND_DETACH

在API級24 INT STOP_FOREGROUND_DETACH標誌添加 stopForeground(INT):如果置位,該通知先前提供給 startForeground(INT,通知)將從服務中分離出來。 只有當STOP_FOREGROUND_REMOVE未設置時纔有意義 - 在此 的情況下,通知將保持顯示,但從服務中完全脫離 ,因此不再發生變化,除非通過直接呼叫 發送到通知管理器。

常量值:2(0x00000002)

所以,startForeground()反覆呼籲後,才能調用stopForeground(STOP_FOREGROUND_DETACH);。這將分離通知,並且重複調用startForeground()將不會對其進行修改,如果您使用不同的通知ID。

此外,「分離」通知現在不代表「正在進行的服務」,因此可以通過用戶用滑動來移除。

獎金:

出於兼容性,可以使用ServiceCompat類及其static方法ServiceCompat.stopForeground(MyService.this, STOP_FOREGROUND_DETACH)如記載here