DownloadService: Minor improvements

* Avoid ActivityManager log spam by only calling startForeground once,
  and subsequently updating the notification via NotificationManager.
* Tweak demo app service to make it a tiny bit easier to swap the Scheduler.

PiperOrigin-RevId: 397179398
This commit is contained in:
olly 2021-09-16 23:10:59 +01:00 committed by Oliver Woodman
parent 6edf9c31bf
commit 4ff4263af3
2 changed files with 13 additions and 3 deletions

View file

@ -26,6 +26,7 @@ import com.google.android.exoplayer2.offline.DownloadManager;
import com.google.android.exoplayer2.offline.DownloadService;
import com.google.android.exoplayer2.scheduler.PlatformScheduler;
import com.google.android.exoplayer2.scheduler.Requirements;
import com.google.android.exoplayer2.scheduler.Scheduler;
import com.google.android.exoplayer2.ui.DownloadNotificationHelper;
import com.google.android.exoplayer2.util.NotificationUtil;
import com.google.android.exoplayer2.util.Util;
@ -61,7 +62,7 @@ public class DemoDownloadService extends DownloadService {
}
@Override
protected PlatformScheduler getScheduler() {
protected Scheduler getScheduler() {
return Util.SDK_INT >= 21 ? new PlatformScheduler(this, JOB_ID) : null;
}

View file

@ -18,6 +18,7 @@ package com.google.android.exoplayer2.offline;
import static com.google.android.exoplayer2.offline.Download.STOP_REASON_NONE;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
@ -889,8 +890,16 @@ public abstract class DownloadService extends Service {
List<Download> downloads = Assertions.checkNotNull(downloadManager).getCurrentDownloads();
@Requirements.RequirementFlags
int notMetRequirements = downloadManager.getNotMetRequirements();
startForeground(notificationId, getForegroundNotification(downloads, notMetRequirements));
notificationDisplayed = true;
Notification notification = getForegroundNotification(downloads, notMetRequirements);
if (!notificationDisplayed) {
startForeground(notificationId, notification);
notificationDisplayed = true;
} else {
// Update the notification via NotificationManager rather than by repeatedly calling
// startForeground, since the latter can cause ActivityManager log spam.
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.notify(notificationId, notification);
}
if (periodicUpdatesStarted) {
handler.removeCallbacksAndMessages(null);
handler.postDelayed(this::update, updateInterval);