我有一個具有兩個服務的應用程序。使用startForeground()調用多個前景服務的單個通知
其中一個用於在其他應用上使用WindowManager
來顯示浮動用戶界面(疊加)。另一個是使用GooglePlayAPI
進行位置跟蹤。我的應用總是運行這些服務。
我希望這些服務不被操作系統殺死。所以我打電話Service.startForeground()
。但通知抽屜中有兩個通知。
有沒有辦法爲這兩種服務使用單個通知?
我有一個具有兩個服務的應用程序。使用startForeground()調用多個前景服務的單個通知
其中一個用於在其他應用上使用WindowManager
來顯示浮動用戶界面(疊加)。另一個是使用GooglePlayAPI
進行位置跟蹤。我的應用總是運行這些服務。
我希望這些服務不被操作系統殺死。所以我打電話Service.startForeground()
。但通知抽屜中有兩個通知。
有沒有辦法爲這兩種服務使用單個通知?
是的,這是可能的。
如果我們看看Service.startForeground()簽名,它接受通知本身(see documentation)的通知ID &。因此,如果我們想要針對多個前臺服務只有單個通知,則這些服務必須共享相同的通知ID通知&。
我們可以使用單例模式獲取相同的通知&通知ID。下面是示例實現:
NotificationCreator.java
public class NotificationCreator {
private static final int NOTIFICATION_ID = 1094;
private static Notification notification;
public static Notification getNotification(Context context) {
if(notification == null) {
notification = new NotificationCompat.Builder(context)
.setContentTitle("Try Foreground Service")
.setContentText("Yuhu..., I'm trying foreground service")
.setSmallIcon(R.mipmap.ic_launcher)
.build();
}
return notification;
}
public static int getNotificationId() {
return NOTIFICATION_ID;
}
}
因此,我們可以在我們的前臺服務使用這個類。例如,我們有MyFirstService.java & MySecondService.java:
MyFirstService.java
public class MyFirstService extends Service {
@Override
public void onCreate() {
super.onCreate();
startForeground(NotificationCreator.getNotificationId(),
NotificationCreator.getNotification(this));
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
MySecondService.java
public class MySecondService extends Service {
@Override
public void onCreate() {
super.onCreate();
startForeground(NotificationCreator.getNotificationId(),
NotificationCreator.getNotification(this));
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
只是嘗試運行這些服務。瞧!你有多個前臺服務的單個通知;)!
如果您使用RemoteViews來定義通知佈局,您仍然會遇到問題... –
android中的兩個通知是指? –
@Pramod在Service中使用startForeground方法時,android系統會設置有關現在運行的Service的通知。我使用兩項服務。並在兩個類中使用startForeground方法。 –
一種選擇是將2個服務合併成一個服務..我知道這並不能回答這個問題。但它可能是您給予兩種服務一起開始和結束的一種選擇。 – Madushan