From be0b2b8c8c496d7e8349d174e8a6c1dfe8d23df9 Mon Sep 17 00:00:00 2001 From: tonihei Date: Thu, 25 Nov 2021 10:01:47 +0000 Subject: [PATCH] Move MediaMetricsListener creation to static constructor method. This allows to check if the media metrics service is available outside the actual constructor and to fail gracefully if it is missing. PiperOrigin-RevId: 412232425 --- .../analytics/MediaMetricsListener.java | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/library/core/src/main/java/com/google/android/exoplayer2/analytics/MediaMetricsListener.java b/library/core/src/main/java/com/google/android/exoplayer2/analytics/MediaMetricsListener.java index f085a6bae1..15340b4e30 100644 --- a/library/core/src/main/java/com/google/android/exoplayer2/analytics/MediaMetricsListener.java +++ b/library/core/src/main/java/com/google/android/exoplayer2/analytics/MediaMetricsListener.java @@ -16,7 +16,6 @@ package com.google.android.exoplayer2.analytics; import static com.google.android.exoplayer2.util.Assertions.checkNotNull; -import static com.google.android.exoplayer2.util.Assertions.checkStateNotNull; import static com.google.android.exoplayer2.util.Util.castNonNull; import android.annotation.SuppressLint; @@ -90,6 +89,23 @@ import org.checkerframework.checker.nullness.qual.RequiresNonNull; public final class MediaMetricsListener implements AnalyticsListener, PlaybackSessionManager.Listener { + /** + * Creates a media metrics listener. + * + * @param context A context. + * @return The {@link MediaMetricsListener}, or null if the {@link Context#MEDIA_METRICS_SERVICE + * media metrics service} isn't available. + */ + @Nullable + public static MediaMetricsListener create(Context context) { + @Nullable + MediaMetricsManager mediaMetricsManager = + (MediaMetricsManager) context.getSystemService(Context.MEDIA_METRICS_SERVICE); + return mediaMetricsManager == null + ? null + : new MediaMetricsListener(context, mediaMetricsManager.createPlaybackSession()); + } + private final Context context; private final PlaybackSessionManager sessionManager; private final PlaybackSession playbackSession; @@ -122,15 +138,12 @@ public final class MediaMetricsListener * * @param context A {@link Context}. */ - public MediaMetricsListener(Context context) { + private MediaMetricsListener(Context context, PlaybackSession playbackSession) { context = context.getApplicationContext(); this.context = context; + this.playbackSession = playbackSession; window = new Timeline.Window(); period = new Timeline.Period(); - MediaMetricsManager mediaMetricsManager = - checkStateNotNull( - (MediaMetricsManager) context.getSystemService(Context.MEDIA_METRICS_SERVICE)); - playbackSession = mediaMetricsManager.createPlaybackSession(); startTimeMs = SystemClock.elapsedRealtime(); currentPlaybackState = PlaybackStateEvent.STATE_NOT_STARTED; currentNetworkType = NetworkEvent.NETWORK_TYPE_UNKNOWN;