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
This commit is contained in:
tonihei 2021-11-25 10:01:47 +00:00 committed by kim-vde
parent 94ef005b17
commit be0b2b8c8c

View file

@ -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;