Use lamdas everywhere

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=209162373
This commit is contained in:
olly 2018-08-17 09:49:03 -07:00 committed by Oliver Woodman
parent 0831f6cab3
commit bd8a956d53
60 changed files with 541 additions and 1305 deletions

View File

@ -30,8 +30,6 @@ import android.view.Menu;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener; import android.view.View.OnClickListener;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter; import android.widget.ArrayAdapter;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
@ -145,13 +143,9 @@ public class MainActivity extends AppCompatActivity implements OnClickListener,
ListView sampleList = dialogList.findViewById(R.id.sample_list); ListView sampleList = dialogList.findViewById(R.id.sample_list);
sampleList.setAdapter(new SampleListAdapter(this)); sampleList.setAdapter(new SampleListAdapter(this));
sampleList.setOnItemClickListener( sampleList.setOnItemClickListener(
new OnItemClickListener() { (parent, view, position, id) -> {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
playerManager.addItem(DemoUtil.SAMPLES.get(position)); playerManager.addItem(DemoUtil.SAMPLES.get(position));
mediaQueueListAdapter.notifyItemInserted(playerManager.getMediaQueueSize() - 1); mediaQueueListAdapter.notifyItemInserted(playerManager.getMediaQueueSize() - 1);
}
}); });
return dialogList; return dialogList;
} }

View File

@ -175,15 +175,12 @@ public class DownloadTracker implements DownloadManager.Listener {
} }
final DownloadAction[] actions = trackedDownloadStates.values().toArray(new DownloadAction[0]); final DownloadAction[] actions = trackedDownloadStates.values().toArray(new DownloadAction[0]);
actionFileWriteHandler.post( actionFileWriteHandler.post(
new Runnable() { () -> {
@Override
public void run() {
try { try {
actionFile.store(actions); actionFile.store(actions);
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "Failed to store tracked actions", e); Log.e(TAG, "Failed to store tracked actions", e);
} }
}
}); });
} }

View File

@ -60,8 +60,6 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.ShadowSystemClock; import org.robolectric.shadows.ShadowSystemClock;
@ -170,16 +168,13 @@ public final class CronetDataSourceTest {
final UrlRequest mockUrlRequest2 = mock(UrlRequest.class); final UrlRequest mockUrlRequest2 = mock(UrlRequest.class);
when(mockUrlRequestBuilder.build()).thenReturn(mockUrlRequest2); when(mockUrlRequestBuilder.build()).thenReturn(mockUrlRequest2);
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
// Invoke the callback for the previous request. // Invoke the callback for the previous request.
dataSourceUnderTest.urlRequestCallback.onFailed( dataSourceUnderTest.urlRequestCallback.onFailed(
mockUrlRequest, testUrlResponseInfo, mockNetworkException); mockUrlRequest, testUrlResponseInfo, mockNetworkException);
dataSourceUnderTest.urlRequestCallback.onResponseStarted( dataSourceUnderTest.urlRequestCallback.onResponseStarted(
mockUrlRequest2, testUrlResponseInfo); mockUrlRequest2, testUrlResponseInfo);
return null; return null;
}
}) })
.when(mockUrlRequest2) .when(mockUrlRequest2)
.start(); .start();
@ -900,14 +895,11 @@ public final class CronetDataSourceTest {
private void mockStatusResponse() { private void mockStatusResponse() {
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
UrlRequest.StatusListener statusListener = UrlRequest.StatusListener statusListener =
(UrlRequest.StatusListener) invocation.getArguments()[0]; (UrlRequest.StatusListener) invocation.getArguments()[0];
statusListener.onStatus(TEST_CONNECTION_STATUS); statusListener.onStatus(TEST_CONNECTION_STATUS);
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.getStatus(any(UrlRequest.StatusListener.class)); .getStatus(any(UrlRequest.StatusListener.class));
@ -915,13 +907,10 @@ public final class CronetDataSourceTest {
private void mockResponseStartSuccess() { private void mockResponseStartSuccess() {
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
dataSourceUnderTest.urlRequestCallback.onResponseStarted( dataSourceUnderTest.urlRequestCallback.onResponseStarted(
mockUrlRequest, testUrlResponseInfo); mockUrlRequest, testUrlResponseInfo);
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.start(); .start();
@ -929,15 +918,12 @@ public final class CronetDataSourceTest {
private void mockResponseStartRedirect() { private void mockResponseStartRedirect() {
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
dataSourceUnderTest.urlRequestCallback.onRedirectReceived( dataSourceUnderTest.urlRequestCallback.onRedirectReceived(
mockUrlRequest, mockUrlRequest,
createUrlResponseInfo(307), // statusCode createUrlResponseInfo(307), // statusCode
"http://redirect.location.com"); "http://redirect.location.com");
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.start(); .start();
@ -945,9 +931,7 @@ public final class CronetDataSourceTest {
private void mockSingleRedirectSuccess() { private void mockSingleRedirectSuccess() {
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
if (!redirectCalled) { if (!redirectCalled) {
redirectCalled = true; redirectCalled = true;
dataSourceUnderTest.urlRequestCallback.onRedirectReceived( dataSourceUnderTest.urlRequestCallback.onRedirectReceived(
@ -959,7 +943,6 @@ public final class CronetDataSourceTest {
mockUrlRequest, testUrlResponseInfo); mockUrlRequest, testUrlResponseInfo);
} }
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.start(); .start();
@ -967,13 +950,10 @@ public final class CronetDataSourceTest {
private void mockFollowRedirectSuccess() { private void mockFollowRedirectSuccess() {
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
dataSourceUnderTest.urlRequestCallback.onResponseStarted( dataSourceUnderTest.urlRequestCallback.onResponseStarted(
mockUrlRequest, testUrlResponseInfo); mockUrlRequest, testUrlResponseInfo);
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.followRedirect(); .followRedirect();
@ -981,15 +961,12 @@ public final class CronetDataSourceTest {
private void mockResponseStartFailure() { private void mockResponseStartFailure() {
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
dataSourceUnderTest.urlRequestCallback.onFailed( dataSourceUnderTest.urlRequestCallback.onFailed(
mockUrlRequest, mockUrlRequest,
createUrlResponseInfo(500), // statusCode createUrlResponseInfo(500), // statusCode
mockNetworkException); mockNetworkException);
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.start(); .start();
@ -998,9 +975,7 @@ public final class CronetDataSourceTest {
private void mockReadSuccess(int position, int length) { private void mockReadSuccess(int position, int length) {
final int[] positionAndRemaining = new int[] {position, length}; final int[] positionAndRemaining = new int[] {position, length};
doAnswer( doAnswer(
new Answer<Void>() { invocation -> {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
if (positionAndRemaining[1] == 0) { if (positionAndRemaining[1] == 0) {
dataSourceUnderTest.urlRequestCallback.onSucceeded( dataSourceUnderTest.urlRequestCallback.onSucceeded(
mockUrlRequest, testUrlResponseInfo); mockUrlRequest, testUrlResponseInfo);
@ -1014,7 +989,6 @@ public final class CronetDataSourceTest {
mockUrlRequest, testUrlResponseInfo, inputBuffer); mockUrlRequest, testUrlResponseInfo, inputBuffer);
} }
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.read(any(ByteBuffer.class)); .read(any(ByteBuffer.class));
@ -1022,15 +996,12 @@ public final class CronetDataSourceTest {
private void mockReadFailure() { private void mockReadFailure() {
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
dataSourceUnderTest.urlRequestCallback.onFailed( dataSourceUnderTest.urlRequestCallback.onFailed(
mockUrlRequest, mockUrlRequest,
createUrlResponseInfo(500), // statusCode createUrlResponseInfo(500), // statusCode
mockNetworkException); mockNetworkException);
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.read(any(ByteBuffer.class)); .read(any(ByteBuffer.class));
@ -1039,12 +1010,9 @@ public final class CronetDataSourceTest {
private ConditionVariable buildReadStartedCondition() { private ConditionVariable buildReadStartedCondition() {
final ConditionVariable startedCondition = new ConditionVariable(); final ConditionVariable startedCondition = new ConditionVariable();
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
startedCondition.open(); startedCondition.open();
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.read(any(ByteBuffer.class)); .read(any(ByteBuffer.class));
@ -1054,12 +1022,9 @@ public final class CronetDataSourceTest {
private ConditionVariable buildUrlRequestStartedCondition() { private ConditionVariable buildUrlRequestStartedCondition() {
final ConditionVariable startedCondition = new ConditionVariable(); final ConditionVariable startedCondition = new ConditionVariable();
doAnswer( doAnswer(
new Answer<Object>() { invocation -> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
startedCondition.open(); startedCondition.open();
return null; return null;
}
}) })
.when(mockUrlRequest) .when(mockUrlRequest)
.start(); .start();

View File

@ -16,9 +16,7 @@
package com.google.android.exoplayer2.ext.flac; package com.google.android.exoplayer2.ext.flac;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
/** /**
* Unit test for {@link FlacExtractor}. * Unit test for {@link FlacExtractor}.
@ -35,25 +33,11 @@ public class FlacExtractorTest extends InstrumentationTestCase {
public void testExtractFlacSample() throws Exception { public void testExtractFlacSample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(
new ExtractorFactory() { FlacExtractor::new, "bear.flac", getInstrumentation().getContext());
@Override
public Extractor create() {
return new FlacExtractor();
}
},
"bear.flac",
getInstrumentation().getContext());
} }
public void testExtractFlacSampleWithId3Header() throws Exception { public void testExtractFlacSampleWithId3Header() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(
new ExtractorFactory() { FlacExtractor::new, "bear_with_id3.flac", getInstrumentation().getContext());
@Override
public Extractor create() {
return new FlacExtractor();
}
},
"bear_with_id3.flac",
getInstrumentation().getContext());
} }
} }

View File

@ -853,16 +853,13 @@ import java.util.Collections;
private void sendMessageToTargetThread(final PlayerMessage message) { private void sendMessageToTargetThread(final PlayerMessage message) {
Handler handler = message.getHandler(); Handler handler = message.getHandler();
handler.post( handler.post(
new Runnable() { () -> {
@Override
public void run() {
try { try {
deliverMessage(message); deliverMessage(message);
} catch (ExoPlaybackException e) { } catch (ExoPlaybackException e) {
Log.e(TAG, "Unexpected error delivering message on external thread.", e); Log.e(TAG, "Unexpected error delivering message on external thread.", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
}
}); });
} }

View File

@ -104,12 +104,7 @@ public interface AudioRendererEventListener {
*/ */
public void enabled(final DecoderCounters decoderCounters) { public void enabled(final DecoderCounters decoderCounters) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(() -> listener.onAudioEnabled(decoderCounters));
@Override
public void run() {
listener.onAudioEnabled(decoderCounters);
}
});
} }
} }
@ -119,13 +114,10 @@ public interface AudioRendererEventListener {
public void decoderInitialized(final String decoderName, public void decoderInitialized(final String decoderName,
final long initializedTimestampMs, final long initializationDurationMs) { final long initializedTimestampMs, final long initializationDurationMs) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(
@Override () ->
public void run() { listener.onAudioDecoderInitialized(
listener.onAudioDecoderInitialized(decoderName, initializedTimestampMs, decoderName, initializedTimestampMs, initializationDurationMs));
initializationDurationMs);
}
});
} }
} }
@ -134,12 +126,7 @@ public interface AudioRendererEventListener {
*/ */
public void inputFormatChanged(final Format format) { public void inputFormatChanged(final Format format) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(() -> listener.onAudioInputFormatChanged(format));
@Override
public void run() {
listener.onAudioInputFormatChanged(format);
}
});
} }
} }
@ -149,12 +136,8 @@ public interface AudioRendererEventListener {
public void audioTrackUnderrun(final int bufferSize, final long bufferSizeMs, public void audioTrackUnderrun(final int bufferSize, final long bufferSizeMs,
final long elapsedSinceLastFeedMs) { final long elapsedSinceLastFeedMs) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(
@Override () -> listener.onAudioSinkUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs));
public void run() {
listener.onAudioSinkUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs);
}
});
} }
} }
@ -163,12 +146,10 @@ public interface AudioRendererEventListener {
*/ */
public void disabled(final DecoderCounters counters) { public void disabled(final DecoderCounters counters) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(
@Override () -> {
public void run() {
counters.ensureUpdated(); counters.ensureUpdated();
listener.onAudioDisabled(counters); listener.onAudioDisabled(counters);
}
}); });
} }
} }
@ -178,12 +159,7 @@ public interface AudioRendererEventListener {
*/ */
public void audioSessionId(final int audioSessionId) { public void audioSessionId(final int audioSessionId) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(() -> listener.onAudioSessionId(audioSessionId));
@Override
public void run() {
listener.onAudioSessionId(audioSessionId);
}
});
} }
} }

View File

@ -24,8 +24,6 @@ import android.media.MediaDrm;
import android.media.MediaDrmException; import android.media.MediaDrmException;
import android.media.NotProvisionedException; import android.media.NotProvisionedException;
import android.media.UnsupportedSchemeException; import android.media.UnsupportedSchemeException;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.extractor.mp4.PsshAtomUtil; import com.google.android.exoplayer2.extractor.mp4.PsshAtomUtil;
import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Assertions;
@ -80,13 +78,11 @@ public final class FrameworkMediaDrm implements ExoMediaDrm<FrameworkMediaCrypto
@Override @Override
public void setOnEventListener( public void setOnEventListener(
final ExoMediaDrm.OnEventListener<? super FrameworkMediaCrypto> listener) { final ExoMediaDrm.OnEventListener<? super FrameworkMediaCrypto> listener) {
mediaDrm.setOnEventListener(listener == null ? null : new MediaDrm.OnEventListener() { mediaDrm.setOnEventListener(
@Override listener == null
public void onEvent(@NonNull MediaDrm md, @Nullable byte[] sessionId, int event, int extra, ? null
byte[] data) { : (mediaDrm, sessionId, event, extra, data) ->
listener.onEvent(FrameworkMediaDrm.this, sessionId, event, extra, data); listener.onEvent(FrameworkMediaDrm.this, sessionId, event, extra, data));
}
});
} }
@Override @Override
@ -99,20 +95,13 @@ public final class FrameworkMediaDrm implements ExoMediaDrm<FrameworkMediaCrypto
mediaDrm.setOnKeyStatusChangeListener( mediaDrm.setOnKeyStatusChangeListener(
listener == null listener == null
? null ? null
: new MediaDrm.OnKeyStatusChangeListener() { : (mediaDrm, sessionId, keyInfo, hasNewUsableKey) -> {
@Override
public void onKeyStatusChange(
@NonNull MediaDrm md,
@NonNull byte[] sessionId,
@NonNull List<MediaDrm.KeyStatus> keyInfo,
boolean hasNewUsableKey) {
List<KeyStatus> exoKeyInfo = new ArrayList<>(); List<KeyStatus> exoKeyInfo = new ArrayList<>();
for (MediaDrm.KeyStatus keyStatus : keyInfo) { for (MediaDrm.KeyStatus keyStatus : keyInfo) {
exoKeyInfo.add(new KeyStatus(keyStatus.getStatusCode(), keyStatus.getKeyId())); exoKeyInfo.add(new KeyStatus(keyStatus.getStatusCode(), keyStatus.getKeyId()));
} }
listener.onKeyStatusChange( listener.onKeyStatusChange(
FrameworkMediaDrm.this, sessionId, exoKeyInfo, hasNewUsableKey); FrameworkMediaDrm.this, sessionId, exoKeyInfo, hasNewUsableKey);
}
}, },
null); null);
} }

View File

@ -29,16 +29,13 @@ import java.util.regex.Pattern;
public final class GaplessInfoHolder { public final class GaplessInfoHolder {
/** /**
* A {@link FramePredicate} suitable for use when decoding {@link Metadata} that will be passed * A {@link FramePredicate} suitable for use when decoding {@link Metadata} that will be passed to
* to {@link #setFromMetadata(Metadata)}. Only frames that might contain gapless playback * {@link #setFromMetadata(Metadata)}. Only frames that might contain gapless playback information
* information are decoded. * are decoded.
*/ */
public static final FramePredicate GAPLESS_INFO_ID3_FRAME_PREDICATE = new FramePredicate() { public static final FramePredicate GAPLESS_INFO_ID3_FRAME_PREDICATE =
@Override (majorVersion, id0, id1, id2, id3) ->
public boolean evaluate(int majorVersion, int id0, int id1, int id2, int id3) { id0 == 'C' && id1 == 'O' && id2 == 'M' && (id3 == 'M' || majorVersion == 2);
return id0 == 'C' && id1 == 'O' && id2 == 'M' && (id3 == 'M' || majorVersion == 2);
}
};
private static final String GAPLESS_DOMAIN = "com.apple.iTunes"; private static final String GAPLESS_DOMAIN = "com.apple.iTunes";
private static final String GAPLESS_DESCRIPTION = "iTunSMPB"; private static final String GAPLESS_DESCRIPTION = "iTunSMPB";

View File

@ -56,13 +56,7 @@ public final class Id3Decoder implements MetadataDecoder {
/** A predicate that indicates no frames should be decoded. */ /** A predicate that indicates no frames should be decoded. */
public static final FramePredicate NO_FRAMES_PREDICATE = public static final FramePredicate NO_FRAMES_PREDICATE =
new FramePredicate() { (majorVersion, id0, id1, id2, id3) -> false;
@Override
public boolean evaluate(int majorVersion, int id0, int id1, int id2, int id3) {
return false;
}
};
private static final String TAG = "Id3Decoder"; private static final String TAG = "Id3Decoder";

View File

@ -59,21 +59,9 @@ public abstract class DownloadHelper {
public void run() { public void run() {
try { try {
prepareInternal(); prepareInternal();
handler.post( handler.post(() -> callback.onPrepared(DownloadHelper.this));
new Runnable() {
@Override
public void run() {
callback.onPrepared(DownloadHelper.this);
}
});
} catch (final IOException e) { } catch (final IOException e) {
handler.post( handler.post(() -> callback.onPrepareError(DownloadHelper.this, e));
new Runnable() {
@Override
public void run() {
callback.onPrepareError(DownloadHelper.this, e);
}
});
} }
} }
}.start(); }.start();

View File

@ -336,12 +336,7 @@ public final class DownloadManager {
tasks.get(i).stop(); tasks.get(i).stop();
} }
final ConditionVariable fileIOFinishedCondition = new ConditionVariable(); final ConditionVariable fileIOFinishedCondition = new ConditionVariable();
fileIOHandler.post(new Runnable() { fileIOHandler.post(fileIOFinishedCondition::open);
@Override
public void run() {
fileIOFinishedCondition.open();
}
});
fileIOFinishedCondition.block(); fileIOFinishedCondition.block();
fileIOThread.quit(); fileIOThread.quit();
logd("Released"); logd("Released");
@ -451,9 +446,7 @@ public final class DownloadManager {
private void loadActions() { private void loadActions() {
fileIOHandler.post( fileIOHandler.post(
new Runnable() { () -> {
@Override
public void run() {
DownloadAction[] loadedActions; DownloadAction[] loadedActions;
try { try {
loadedActions = actionFile.load(DownloadManager.this.deserializers); loadedActions = actionFile.load(DownloadManager.this.deserializers);
@ -464,9 +457,7 @@ public final class DownloadManager {
} }
final DownloadAction[] actions = loadedActions; final DownloadAction[] actions = loadedActions;
handler.post( handler.post(
new Runnable() { () -> {
@Override
public void run() {
if (released) { if (released) {
return; return;
} }
@ -493,9 +484,7 @@ public final class DownloadManager {
notifyListenersTaskStateChange(task); notifyListenersTaskStateChange(task);
} }
} }
}
}); });
}
}); });
} }
@ -507,16 +496,14 @@ public final class DownloadManager {
for (int i = 0; i < tasks.size(); i++) { for (int i = 0; i < tasks.size(); i++) {
actions[i] = tasks.get(i).action; actions[i] = tasks.get(i).action;
} }
fileIOHandler.post(new Runnable() { fileIOHandler.post(
@Override () -> {
public void run() {
try { try {
actionFile.store(actions); actionFile.store(actions);
logd("Actions persisted."); logd("Actions persisted.");
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "Persisting actions failed.", e); Log.e(TAG, "Persisting actions failed.", e);
} }
}
}); });
} }
@ -771,12 +758,7 @@ public final class DownloadManager {
private void cancel() { private void cancel() {
if (changeStateAndNotify(STATE_QUEUED, STATE_QUEUED_CANCELING)) { if (changeStateAndNotify(STATE_QUEUED, STATE_QUEUED_CANCELING)) {
downloadManager.handler.post( downloadManager.handler.post(
new Runnable() { () -> changeStateAndNotify(STATE_QUEUED_CANCELING, STATE_CANCELED));
@Override
public void run() {
changeStateAndNotify(STATE_QUEUED_CANCELING, STATE_CANCELED);
}
});
} else if (changeStateAndNotify(STATE_STARTED, STATE_STARTED_CANCELING)) { } else if (changeStateAndNotify(STATE_STARTED, STATE_STARTED_CANCELING)) {
cancelDownload(); cancelDownload();
} }
@ -851,19 +833,14 @@ public final class DownloadManager {
} }
final Throwable finalError = error; final Throwable finalError = error;
downloadManager.handler.post( downloadManager.handler.post(
new Runnable() { () -> {
@Override
public void run() {
if (changeStateAndNotify( if (changeStateAndNotify(
STATE_STARTED, STATE_STARTED, finalError != null ? STATE_FAILED : STATE_COMPLETED, finalError)
finalError != null ? STATE_FAILED : STATE_COMPLETED,
finalError)
|| changeStateAndNotify(STATE_STARTED_CANCELING, STATE_CANCELED) || changeStateAndNotify(STATE_STARTED_CANCELING, STATE_CANCELED)
|| changeStateAndNotify(STATE_STARTED_STOPPING, STATE_QUEUED)) { || changeStateAndNotify(STATE_STARTED_STOPPING, STATE_QUEUED)) {
return; return;
} }
throw new IllegalStateException(); throw new IllegalStateException();
}
}); });
} }

View File

@ -101,13 +101,7 @@ public abstract class CompositeMediaSource<T> extends BaseMediaSource {
protected final void prepareChildSource(final T id, MediaSource mediaSource) { protected final void prepareChildSource(final T id, MediaSource mediaSource) {
Assertions.checkArgument(!childSources.containsKey(id)); Assertions.checkArgument(!childSources.containsKey(id));
SourceInfoRefreshListener sourceListener = SourceInfoRefreshListener sourceListener =
new SourceInfoRefreshListener() { (source, timeline, manifest) -> onChildSourceInfoRefreshed(id, source, timeline, manifest);
@Override
public void onSourceInfoRefreshed(
MediaSource source, Timeline timeline, @Nullable Object manifest) {
onChildSourceInfoRefreshed(id, source, timeline, manifest);
}
};
MediaSourceEventListener eventListener = new ForwardingEventListener(id); MediaSourceEventListener eventListener = new ForwardingEventListener(id);
childSources.put(id, new MediaSourceAndListener(mediaSource, sourceListener, eventListener)); childSources.put(id, new MediaSourceAndListener(mediaSource, sourceListener, eventListener));
mediaSource.addEventListener(Assertions.checkNotNull(eventHandler), eventListener); mediaSource.addEventListener(Assertions.checkNotNull(eventHandler), eventListener);

View File

@ -325,12 +325,7 @@ public final class AdsMediaSource extends CompositeMediaSource<MediaPeriodId> {
final ComponentListener componentListener = new ComponentListener(); final ComponentListener componentListener = new ComponentListener();
this.componentListener = componentListener; this.componentListener = componentListener;
prepareChildSource(DUMMY_CONTENT_MEDIA_PERIOD_ID, contentMediaSource); prepareChildSource(DUMMY_CONTENT_MEDIA_PERIOD_ID, contentMediaSource);
mainHandler.post(new Runnable() { mainHandler.post(() -> adsLoader.attachPlayer(player, componentListener, adUiViewGroup));
@Override
public void run() {
adsLoader.attachPlayer(player, componentListener, adUiViewGroup);
}
});
} }
@Override @Override
@ -397,12 +392,7 @@ public final class AdsMediaSource extends CompositeMediaSource<MediaPeriodId> {
adPlaybackState = null; adPlaybackState = null;
adGroupMediaSources = new MediaSource[0][]; adGroupMediaSources = new MediaSource[0][];
adDurationsUs = new long[0][]; adDurationsUs = new long[0][];
mainHandler.post(new Runnable() { mainHandler.post(adsLoader::detachPlayer);
@Override
public void run() {
adsLoader.detachPlayer();
}
});
} }
@Override @Override
@ -500,14 +490,12 @@ public final class AdsMediaSource extends CompositeMediaSource<MediaPeriodId> {
if (released) { if (released) {
return; return;
} }
playerHandler.post(new Runnable() { playerHandler.post(
@Override () -> {
public void run() {
if (released) { if (released) {
return; return;
} }
AdsMediaSource.this.onAdPlaybackState(adPlaybackState); AdsMediaSource.this.onAdPlaybackState(adPlaybackState);
}
}); });
} }
@ -517,13 +505,11 @@ public final class AdsMediaSource extends CompositeMediaSource<MediaPeriodId> {
return; return;
} }
if (eventHandler != null && eventListener != null) { if (eventHandler != null && eventListener != null) {
eventHandler.post(new Runnable() { eventHandler.post(
@Override () -> {
public void run() {
if (!released) { if (!released) {
eventListener.onAdClicked(); eventListener.onAdClicked();
} }
}
}); });
} }
} }
@ -534,13 +520,11 @@ public final class AdsMediaSource extends CompositeMediaSource<MediaPeriodId> {
return; return;
} }
if (eventHandler != null && eventListener != null) { if (eventHandler != null && eventListener != null) {
eventHandler.post(new Runnable() { eventHandler.post(
@Override () -> {
public void run() {
if (!released) { if (!released) {
eventListener.onAdTapped(); eventListener.onAdTapped();
} }
}
}); });
} }
} }
@ -562,9 +546,7 @@ public final class AdsMediaSource extends CompositeMediaSource<MediaPeriodId> {
/* wasCanceled= */ true); /* wasCanceled= */ true);
if (eventHandler != null && eventListener != null) { if (eventHandler != null && eventListener != null) {
eventHandler.post( eventHandler.post(
new Runnable() { () -> {
@Override
public void run() {
if (!released) { if (!released) {
if (error.type == AdLoadException.TYPE_UNEXPECTED) { if (error.type == AdLoadException.TYPE_UNEXPECTED) {
eventListener.onInternalAdLoadError(error.getRuntimeExceptionForUnexpected()); eventListener.onInternalAdLoadError(error.getRuntimeExceptionForUnexpected());
@ -572,7 +554,6 @@ public final class AdsMediaSource extends CompositeMediaSource<MediaPeriodId> {
eventListener.onAdLoadError(error); eventListener.onAdLoadError(error);
} }
} }
}
}); });
} }
} }
@ -603,12 +584,7 @@ public final class AdsMediaSource extends CompositeMediaSource<MediaPeriodId> {
AdLoadException.createForAd(exception), AdLoadException.createForAd(exception),
/* wasCanceled= */ true); /* wasCanceled= */ true);
mainHandler.post( mainHandler.post(
new Runnable() { () -> adsLoader.handlePrepareError(adGroupIndex, adIndexInAdGroup, exception));
@Override
public void run() {
adsLoader.handlePrepareError(adGroupIndex, adIndexInAdGroup, exception);
}
});
} }
} }
} }

View File

@ -27,12 +27,7 @@ public final class DummyDataSource implements DataSource {
public static final DummyDataSource INSTANCE = new DummyDataSource(); public static final DummyDataSource INSTANCE = new DummyDataSource();
/** A factory that produces {@link DummyDataSource}. */ /** A factory that produces {@link DummyDataSource}. */
public static final Factory FACTORY = new Factory() { public static final Factory FACTORY = DummyDataSource::new;
@Override
public DataSource createDataSource() {
return new DummyDataSource();
}
};
private DummyDataSource() {} private DummyDataSource() {}

View File

@ -211,19 +211,14 @@ public interface HttpDataSource extends DataSource {
} }
/** /** A {@link Predicate} that rejects content types often used for pay-walls. */
* A {@link Predicate} that rejects content types often used for pay-walls. Predicate<String> REJECT_PAYWALL_TYPES =
*/ contentType -> {
Predicate<String> REJECT_PAYWALL_TYPES = new Predicate<String>() {
@Override
public boolean evaluate(String contentType) {
contentType = Util.toLowerInvariant(contentType); contentType = Util.toLowerInvariant(contentType);
return !TextUtils.isEmpty(contentType) return !TextUtils.isEmpty(contentType)
&& (!contentType.contains("text") || contentType.contains("text/vtt")) && (!contentType.contains("text") || contentType.contains("text/vtt"))
&& !contentType.contains("html") && !contentType.contains("xml"); && !contentType.contains("html")
} && !contentType.contains("xml");
}; };
/** /**

View File

@ -55,13 +55,7 @@ public final class CacheUtil {
public static final int DEFAULT_BUFFER_SIZE_BYTES = 128 * 1024; public static final int DEFAULT_BUFFER_SIZE_BYTES = 128 * 1024;
/** Default {@link CacheKeyFactory} that calls through to {@link #getKey}. */ /** Default {@link CacheKeyFactory} that calls through to {@link #getKey}. */
public static final CacheKeyFactory DEFAULT_CACHE_KEY_FACTORY = public static final CacheKeyFactory DEFAULT_CACHE_KEY_FACTORY = CacheUtil::getKey;
new CacheKeyFactory() {
@Override
public String buildCacheKey(DataSpec dataSpec) {
return getKey(dataSpec);
}
};
/** /**
* Generates a cache key out of the given {@link Uri}. * Generates a cache key out of the given {@link Uri}.

View File

@ -35,19 +35,9 @@ import java.util.Comparator;
public class SlidingPercentile { public class SlidingPercentile {
// Orderings. // Orderings.
private static final Comparator<Sample> INDEX_COMPARATOR = new Comparator<Sample>() { private static final Comparator<Sample> INDEX_COMPARATOR = (a, b) -> a.index - b.index;
@Override private static final Comparator<Sample> VALUE_COMPARATOR =
public int compare(Sample a, Sample b) { (a, b) -> Float.compare(a.value, b.value);
return a.index - b.index;
}
};
private static final Comparator<Sample> VALUE_COMPARATOR = new Comparator<Sample>() {
@Override
public int compare(Sample a, Sample b) {
return a.value < b.value ? -1 : b.value < a.value ? 1 : 0;
}
};
private static final int SORT_ORDER_NONE = -1; private static final int SORT_ORDER_NONE = -1;
private static final int SORT_ORDER_BY_VALUE = 0; private static final int SORT_ORDER_BY_VALUE = 0;

View File

@ -34,7 +34,6 @@ import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.os.Parcel; import android.os.Parcel;
import android.security.NetworkSecurityPolicy; import android.security.NetworkSecurityPolicy;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
import android.text.TextUtils; import android.text.TextUtils;
@ -67,7 +66,6 @@ import java.util.TimeZone;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.zip.DataFormatException; import java.util.zip.DataFormatException;
@ -341,12 +339,7 @@ public final class Util {
* @return The executor. * @return The executor.
*/ */
public static ExecutorService newSingleThreadExecutor(final String threadName) { public static ExecutorService newSingleThreadExecutor(final String threadName) {
return Executors.newSingleThreadExecutor(new ThreadFactory() { return Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, threadName));
@Override
public Thread newThread(@NonNull Runnable r) {
return new Thread(r, threadName);
}
});
} }
/** /**

View File

@ -129,12 +129,7 @@ public interface VideoRendererEventListener {
*/ */
public void enabled(final DecoderCounters decoderCounters) { public void enabled(final DecoderCounters decoderCounters) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(() -> listener.onVideoEnabled(decoderCounters));
@Override
public void run() {
listener.onVideoEnabled(decoderCounters);
}
});
} }
} }
@ -144,13 +139,10 @@ public interface VideoRendererEventListener {
public void decoderInitialized(final String decoderName, public void decoderInitialized(final String decoderName,
final long initializedTimestampMs, final long initializationDurationMs) { final long initializedTimestampMs, final long initializationDurationMs) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(
@Override () ->
public void run() { listener.onVideoDecoderInitialized(
listener.onVideoDecoderInitialized(decoderName, initializedTimestampMs, decoderName, initializedTimestampMs, initializationDurationMs));
initializationDurationMs);
}
});
} }
} }
@ -159,12 +151,7 @@ public interface VideoRendererEventListener {
*/ */
public void inputFormatChanged(final Format format) { public void inputFormatChanged(final Format format) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(() -> listener.onVideoInputFormatChanged(format));
@Override
public void run() {
listener.onVideoInputFormatChanged(format);
}
});
} }
} }
@ -173,12 +160,7 @@ public interface VideoRendererEventListener {
*/ */
public void droppedFrames(final int droppedFrameCount, final long elapsedMs) { public void droppedFrames(final int droppedFrameCount, final long elapsedMs) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(() -> listener.onDroppedFrames(droppedFrameCount, elapsedMs));
@Override
public void run() {
listener.onDroppedFrames(droppedFrameCount, elapsedMs);
}
});
} }
} }
@ -188,13 +170,10 @@ public interface VideoRendererEventListener {
public void videoSizeChanged(final int width, final int height, public void videoSizeChanged(final int width, final int height,
final int unappliedRotationDegrees, final float pixelWidthHeightRatio) { final int unappliedRotationDegrees, final float pixelWidthHeightRatio) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(
@Override () ->
public void run() { listener.onVideoSizeChanged(
listener.onVideoSizeChanged(width, height, unappliedRotationDegrees, width, height, unappliedRotationDegrees, pixelWidthHeightRatio));
pixelWidthHeightRatio);
}
});
} }
} }
@ -203,12 +182,7 @@ public interface VideoRendererEventListener {
*/ */
public void renderedFirstFrame(final Surface surface) { public void renderedFirstFrame(final Surface surface) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(() -> listener.onRenderedFirstFrame(surface));
@Override
public void run() {
listener.onRenderedFirstFrame(surface);
}
});
} }
} }
@ -217,12 +191,10 @@ public interface VideoRendererEventListener {
*/ */
public void disabled(final DecoderCounters counters) { public void disabled(final DecoderCounters counters) {
if (listener != null) { if (listener != null) {
handler.post(new Runnable() { handler.post(
@Override () -> {
public void run() {
counters.ensureUpdated(); counters.ensureUpdated();
listener.onVideoDisabled(counters); listener.onVideoDisabled(counters);
}
}); });
} }
} }

View File

@ -277,24 +277,15 @@ public final class ExoPlayerTest {
.waitForTimelineChanged(timeline) .waitForTimelineChanged(timeline)
.prepareSource(secondSource) .prepareSource(secondSource)
.executeRunnable( .executeRunnable(
new Runnable() { () -> {
@Override
public void run() {
try { try {
queuedSourceInfoCountDownLatch.await(); queuedSourceInfoCountDownLatch.await();
} catch (InterruptedException e) { } catch (InterruptedException e) {
// Ignore. // Ignore.
} }
}
}) })
.prepareSource(thirdSource) .prepareSource(thirdSource)
.executeRunnable( .executeRunnable(completePreparationCountDownLatch::countDown)
new Runnable() {
@Override
public void run() {
completePreparationCountDownLatch.countDown();
}
})
.build(); .build();
ExoPlayerTestRunner testRunner = ExoPlayerTestRunner testRunner =
new Builder() new Builder()
@ -436,13 +427,7 @@ public final class ExoPlayerTest {
new ActionSchedule.Builder("testAdGroupWithLoadErrorIsSkipped") new ActionSchedule.Builder("testAdGroupWithLoadErrorIsSkipped")
.pause() .pause()
.waitForPlaybackState(Player.STATE_READY) .waitForPlaybackState(Player.STATE_READY)
.executeRunnable( .executeRunnable(() -> fakeMediaSource.setNewSourceInfo(adErrorTimeline, null))
new Runnable() {
@Override
public void run() {
fakeMediaSource.setNewSourceInfo(adErrorTimeline, null);
}
})
.waitForTimelineChanged(adErrorTimeline) .waitForTimelineChanged(adErrorTimeline)
.play() .play()
.build(); .build();
@ -823,13 +808,7 @@ public final class ExoPlayerTest {
new ActionSchedule.Builder("testDynamicTimelineChangeReason") new ActionSchedule.Builder("testDynamicTimelineChangeReason")
.pause() .pause()
.waitForTimelineChanged(timeline1) .waitForTimelineChanged(timeline1)
.executeRunnable( .executeRunnable(() -> mediaSource.setNewSourceInfo(timeline2, null))
new Runnable() {
@Override
public void run() {
mediaSource.setNewSourceInfo(timeline2, null);
}
})
.waitForTimelineChanged(timeline2) .waitForTimelineChanged(timeline2)
.play() .play()
.build(); .build();
@ -911,26 +890,17 @@ public final class ExoPlayerTest {
.waitForPlaybackState(Player.STATE_BUFFERING) .waitForPlaybackState(Player.STATE_BUFFERING)
// Block until createPeriod has been called on the fake media source. // Block until createPeriod has been called on the fake media source.
.executeRunnable( .executeRunnable(
new Runnable() { () -> {
@Override
public void run() {
try { try {
createPeriodCalledCountDownLatch.await(); createPeriodCalledCountDownLatch.await();
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
}
}) })
// Set playback parameters (while the fake media period is not yet prepared). // Set playback parameters (while the fake media period is not yet prepared).
.setPlaybackParameters(new PlaybackParameters(/* speed= */ 2f, /* pitch= */ 2f)) .setPlaybackParameters(new PlaybackParameters(/* speed= */ 2f, /* pitch= */ 2f))
// Complete preparation of the fake media period. // Complete preparation of the fake media period.
.executeRunnable( .executeRunnable(() -> fakeMediaPeriodHolder[0].setPreparationComplete())
new Runnable() {
@Override
public void run() {
fakeMediaPeriodHolder[0].setPreparationComplete();
}
})
.build(); .build();
new ExoPlayerTestRunner.Builder() new ExoPlayerTestRunner.Builder()
.setMediaSource(mediaSource) .setMediaSource(mediaSource)
@ -1280,13 +1250,7 @@ public final class ExoPlayerTest {
// is still being prepared. The error will be thrown while the player handles the new // is still being prepared. The error will be thrown while the player handles the new
// source info. // source info.
.seek(/* windowIndex= */ 100, /* positionMs= */ 0) .seek(/* windowIndex= */ 100, /* positionMs= */ 0)
.executeRunnable( .executeRunnable(() -> mediaSource.setNewSourceInfo(timeline, /* newManifest= */ null))
new Runnable() {
@Override
public void run() {
mediaSource.setNewSourceInfo(timeline, /* newManifest= */ null);
}
})
.waitForPlaybackState(Player.STATE_IDLE) .waitForPlaybackState(Player.STATE_IDLE)
.build(); .build();
ExoPlayerTestRunner testRunner = ExoPlayerTestRunner testRunner =
@ -1789,13 +1753,7 @@ public final class ExoPlayerTest {
.pause() .pause()
.waitForTimelineChanged(timeline) .waitForTimelineChanged(timeline)
.sendMessage(target, /* positionMs= */ 50) .sendMessage(target, /* positionMs= */ 50)
.executeRunnable( .executeRunnable(() -> mediaSource.setNewSourceInfo(secondTimeline, null))
new Runnable() {
@Override
public void run() {
mediaSource.setNewSourceInfo(secondTimeline, null);
}
})
.waitForTimelineChanged(secondTimeline) .waitForTimelineChanged(secondTimeline)
.play() .play()
.build(); .build();
@ -1868,13 +1826,7 @@ public final class ExoPlayerTest {
.pause() .pause()
.waitForTimelineChanged(timeline) .waitForTimelineChanged(timeline)
.sendMessage(target, /* windowIndex = */ 1, /* positionMs= */ 50) .sendMessage(target, /* windowIndex = */ 1, /* positionMs= */ 50)
.executeRunnable( .executeRunnable(() -> mediaSource.setNewSourceInfo(secondTimeline, null))
new Runnable() {
@Override
public void run() {
mediaSource.setNewSourceInfo(secondTimeline, null);
}
})
.waitForTimelineChanged(secondTimeline) .waitForTimelineChanged(secondTimeline)
.seek(/* windowIndex= */ 0, /* positionMs= */ 0) .seek(/* windowIndex= */ 0, /* positionMs= */ 0)
.play() .play()
@ -1943,13 +1895,7 @@ public final class ExoPlayerTest {
}) })
// Play a bit to ensure message arrived in internal player. // Play a bit to ensure message arrived in internal player.
.playUntilPosition(/* windowIndex= */ 0, /* positionMs= */ 30) .playUntilPosition(/* windowIndex= */ 0, /* positionMs= */ 30)
.executeRunnable( .executeRunnable(() -> message.get().cancel())
new Runnable() {
@Override
public void run() {
message.get().cancel();
}
})
.play() .play()
.build(); .build();
new Builder() new Builder()
@ -1987,13 +1933,7 @@ public final class ExoPlayerTest {
.playUntilPosition(/* windowIndex= */ 0, /* positionMs= */ 51) .playUntilPosition(/* windowIndex= */ 0, /* positionMs= */ 51)
// Seek back, cancel the message, and play past the same position again. // Seek back, cancel the message, and play past the same position again.
.seek(/* positionMs= */ 0) .seek(/* positionMs= */ 0)
.executeRunnable( .executeRunnable(() -> message.get().cancel())
new Runnable() {
@Override
public void run() {
message.get().cancel();
}
})
.play() .play()
.build(); .build();
new Builder() new Builder()
@ -2064,13 +2004,7 @@ public final class ExoPlayerTest {
.playUntilPosition( .playUntilPosition(
/* windowIndex= */ 0, /* windowIndex= */ 0,
/* positionMs= */ C.usToMs(TimelineWindowDefinition.DEFAULT_WINDOW_DURATION_US)) /* positionMs= */ C.usToMs(TimelineWindowDefinition.DEFAULT_WINDOW_DURATION_US))
.executeRunnable( .executeRunnable(() -> mediaSource.setNewSourceInfo(timeline2, /* newManifest= */ null))
new Runnable() {
@Override
public void run() {
mediaSource.setNewSourceInfo(timeline2, /* newManifest= */ null);
}
})
.waitForTimelineChanged(timeline2) .waitForTimelineChanged(timeline2)
.play() .play()
.build(); .build();

View File

@ -17,9 +17,6 @@ package com.google.android.exoplayer2.analytics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler; import android.os.Handler;
import android.os.SystemClock; import android.os.SystemClock;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
@ -35,10 +32,7 @@ import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.Timeline.Window; import com.google.android.exoplayer2.Timeline.Window;
import com.google.android.exoplayer2.audio.AudioRendererEventListener; import com.google.android.exoplayer2.audio.AudioRendererEventListener;
import com.google.android.exoplayer2.decoder.DecoderCounters; import com.google.android.exoplayer2.decoder.DecoderCounters;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.metadata.MetadataOutput;
import com.google.android.exoplayer2.source.ConcatenatingMediaSource; import com.google.android.exoplayer2.source.ConcatenatingMediaSource;
import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MediaSource.MediaPeriodId; import com.google.android.exoplayer2.source.MediaSource.MediaPeriodId;
@ -53,7 +47,6 @@ import com.google.android.exoplayer2.testutil.FakeMediaSource;
import com.google.android.exoplayer2.testutil.FakeRenderer; import com.google.android.exoplayer2.testutil.FakeRenderer;
import com.google.android.exoplayer2.testutil.FakeTimeline; import com.google.android.exoplayer2.testutil.FakeTimeline;
import com.google.android.exoplayer2.testutil.RobolectricUtil; import com.google.android.exoplayer2.testutil.RobolectricUtil;
import com.google.android.exoplayer2.text.TextOutput;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.util.Util; import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener; import com.google.android.exoplayer2.video.VideoRendererEventListener;
@ -601,13 +594,9 @@ public final class AnalyticsCollectorTest {
// Ensure second period is already being read from. // Ensure second period is already being read from.
.playUntilPosition(/* windowIndex= */ 0, /* positionMs= */ periodDurationMs) .playUntilPosition(/* windowIndex= */ 0, /* positionMs= */ periodDurationMs)
.executeRunnable( .executeRunnable(
new Runnable() { () ->
@Override
public void run() {
concatenatedMediaSource.moveMediaSource( concatenatedMediaSource.moveMediaSource(
/* currentIndex= */ 0, /* newIndex= */ 1); /* currentIndex= */ 0, /* newIndex= */ 1))
}
})
.waitForTimelineChanged(/* expectedTimeline= */ null) .waitForTimelineChanged(/* expectedTimeline= */ null)
.play() .play()
.build(); .build();
@ -658,10 +647,6 @@ public final class AnalyticsCollectorTest {
@Test @Test
public void testNotifyExternalEvents() throws Exception { public void testNotifyExternalEvents() throws Exception {
MediaSource mediaSource = new FakeMediaSource(SINGLE_PERIOD_TIMELINE, /* manifest= */ null); MediaSource mediaSource = new FakeMediaSource(SINGLE_PERIOD_TIMELINE, /* manifest= */ null);
final NetworkInfo networkInfo =
((ConnectivityManager)
RuntimeEnvironment.application.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
ActionSchedule actionSchedule = ActionSchedule actionSchedule =
new ActionSchedule.Builder("AnalyticsCollectorTest") new ActionSchedule.Builder("AnalyticsCollectorTest")
.pause() .pause()
@ -689,21 +674,16 @@ public final class AnalyticsCollectorTest {
private static TestAnalyticsListener runAnalyticsTest( private static TestAnalyticsListener runAnalyticsTest(
MediaSource mediaSource, @Nullable ActionSchedule actionSchedule) throws Exception { MediaSource mediaSource, @Nullable ActionSchedule actionSchedule) throws Exception {
RenderersFactory renderersFactory = RenderersFactory renderersFactory =
new RenderersFactory() { (eventHandler,
@Override videoRendererEventListener,
public Renderer[] createRenderers( audioRendererEventListener,
Handler eventHandler, textRendererOutput,
VideoRendererEventListener videoRendererEventListener, metadataRendererOutput,
AudioRendererEventListener audioRendererEventListener, drmSessionManager) ->
TextOutput textRendererOutput, new Renderer[] {
MetadataOutput metadataRendererOutput,
@Nullable DrmSessionManager<FrameworkMediaCrypto> drmSessionManager) {
return new Renderer[] {
new FakeVideoRenderer(eventHandler, videoRendererEventListener), new FakeVideoRenderer(eventHandler, videoRendererEventListener),
new FakeAudioRenderer(eventHandler, audioRendererEventListener) new FakeAudioRenderer(eventHandler, audioRendererEventListener)
}; };
}
};
TestAnalyticsListener listener = new TestAnalyticsListener(); TestAnalyticsListener listener = new TestAnalyticsListener();
try { try {
new ExoPlayerTestRunner.Builder() new ExoPlayerTestRunner.Builder()

View File

@ -21,7 +21,6 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.metadata.id3.ApicFrame; import com.google.android.exoplayer2.metadata.id3.ApicFrame;
import com.google.android.exoplayer2.metadata.id3.CommentFrame; import com.google.android.exoplayer2.metadata.id3.CommentFrame;
import com.google.android.exoplayer2.metadata.id3.Id3Decoder;
import com.google.android.exoplayer2.metadata.id3.Id3DecoderTest; import com.google.android.exoplayer2.metadata.id3.Id3DecoderTest;
import com.google.android.exoplayer2.testutil.FakeExtractorInput; import com.google.android.exoplayer2.testutil.FakeExtractorInput;
import java.io.IOException; import java.io.IOException;
@ -95,12 +94,8 @@ public final class Id3PeekerTest {
Metadata metadata = Metadata metadata =
id3Peeker.peekId3Data( id3Peeker.peekId3Data(
input, input,
new Id3Decoder.FramePredicate() { (majorVersion, id0, id1, id2, id3) ->
@Override id0 == 'C' && id1 == 'O' && id2 == 'M' && id3 == 'M');
public boolean evaluate(int majorVersion, int id0, int id1, int id2, int id3) {
return id0 == 'C' && id1 == 'O' && id2 == 'M' && id3 == 'M';
}
});
assertThat(metadata.length()).isEqualTo(1); assertThat(metadata.length()).isEqualTo(1);
CommentFrame commentFrame = (CommentFrame) metadata.get(0); CommentFrame commentFrame = (CommentFrame) metadata.get(0);

View File

@ -250,15 +250,12 @@ public final class AmrExtractorTest {
@NonNull @NonNull
private static ExtractorAsserts.ExtractorFactory createAmrExtractorFactory(boolean withSeeking) { private static ExtractorAsserts.ExtractorFactory createAmrExtractorFactory(boolean withSeeking) {
return new ExtractorAsserts.ExtractorFactory() { return () -> {
@Override
public Extractor create() {
if (!withSeeking) { if (!withSeeking) {
return new AmrExtractor(); return new AmrExtractor();
} else { } else {
return new AmrExtractor(AmrExtractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING); return new AmrExtractor(AmrExtractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING);
} }
}
}; };
} }
} }

View File

@ -15,9 +15,7 @@
*/ */
package com.google.android.exoplayer2.extractor.flv; package com.google.android.exoplayer2.extractor.flv;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
@ -28,13 +26,6 @@ public final class FlvExtractorTest {
@Test @Test
public void testSample() throws Exception { public void testSample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(FlvExtractor::new, "flv/sample.flv");
new ExtractorFactory() {
@Override
public Extractor create() {
return new FlvExtractor();
}
},
"flv/sample.flv");
} }
} }

View File

@ -15,9 +15,7 @@
*/ */
package com.google.android.exoplayer2.extractor.mkv; package com.google.android.exoplayer2.extractor.mkv;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
@ -28,37 +26,17 @@ public final class MatroskaExtractorTest {
@Test @Test
public void testMkvSample() throws Exception { public void testMkvSample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(MatroskaExtractor::new, "mkv/sample.mkv");
new ExtractorFactory() {
@Override
public Extractor create() {
return new MatroskaExtractor();
}
},
"mkv/sample.mkv");
} }
@Test @Test
public void testWebmSubsampleEncryption() throws Exception { public void testWebmSubsampleEncryption() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(
new ExtractorFactory() { MatroskaExtractor::new, "mkv/subsample_encrypted_noaltref.webm");
@Override
public Extractor create() {
return new MatroskaExtractor();
}
},
"mkv/subsample_encrypted_noaltref.webm");
} }
@Test @Test
public void testWebmSubsampleEncryptionWithAltrefFrames() throws Exception { public void testWebmSubsampleEncryptionWithAltrefFrames() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(MatroskaExtractor::new, "mkv/subsample_encrypted_altref.webm");
new ExtractorFactory() {
@Override
public Extractor create() {
return new MatroskaExtractor();
}
},
"mkv/subsample_encrypted_altref.webm");
} }
} }

View File

@ -15,9 +15,7 @@
*/ */
package com.google.android.exoplayer2.extractor.mp3; package com.google.android.exoplayer2.extractor.mp3;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
@ -28,25 +26,11 @@ public final class Mp3ExtractorTest {
@Test @Test
public void testMp3Sample() throws Exception { public void testMp3Sample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(Mp3Extractor::new, "mp3/bear.mp3");
new ExtractorFactory() {
@Override
public Extractor create() {
return new Mp3Extractor();
}
},
"mp3/bear.mp3");
} }
@Test @Test
public void testTrimmedMp3Sample() throws Exception { public void testTrimmedMp3Sample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(Mp3Extractor::new, "mp3/play-trimmed.mp3");
new ExtractorFactory() {
@Override
public Extractor create() {
return new Mp3Extractor();
}
},
"mp3/play-trimmed.mp3");
} }
} }

View File

@ -16,7 +16,6 @@
package com.google.android.exoplayer2.extractor.mp4; package com.google.android.exoplayer2.extractor.mp4;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory; import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.MimeTypes;
@ -53,11 +52,6 @@ public final class FragmentedMp4ExtractorTest {
} }
private static ExtractorFactory getExtractorFactory(final List<Format> closedCaptionFormats) { private static ExtractorFactory getExtractorFactory(final List<Format> closedCaptionFormats) {
return new ExtractorFactory() { return () -> new FragmentedMp4Extractor(0, null, null, null, closedCaptionFormats);
@Override
public Extractor create() {
return new FragmentedMp4Extractor(0, null, null, null, closedCaptionFormats);
}
};
} }
} }

View File

@ -16,9 +16,7 @@
package com.google.android.exoplayer2.extractor.mp4; package com.google.android.exoplayer2.extractor.mp4;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
@ -30,13 +28,6 @@ public final class Mp4ExtractorTest {
@Test @Test
public void testMp4Sample() throws Exception { public void testMp4Sample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(Mp4Extractor::new, "mp4/sample.mp4");
new ExtractorFactory() {
@Override
public Extractor create() {
return new Mp4Extractor();
}
},
"mp4/sample.mp4");
} }
} }

View File

@ -17,7 +17,6 @@ package com.google.android.exoplayer2.extractor.ogg;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory; import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import com.google.android.exoplayer2.testutil.FakeExtractorInput; import com.google.android.exoplayer2.testutil.FakeExtractorInput;
@ -32,13 +31,7 @@ import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class) @RunWith(RobolectricTestRunner.class)
public final class OggExtractorTest { public final class OggExtractorTest {
private static final ExtractorFactory OGG_EXTRACTOR_FACTORY = private static final ExtractorFactory OGG_EXTRACTOR_FACTORY = OggExtractor::new;
new ExtractorFactory() {
@Override
public Extractor create() {
return new OggExtractor();
}
};
@Test @Test
public void testOpus() throws Exception { public void testOpus() throws Exception {

View File

@ -17,9 +17,7 @@ package com.google.android.exoplayer2.extractor.rawcc;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.MimeTypes;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -33,10 +31,8 @@ public final class RawCcExtractorTest {
@Test @Test
public void testRawCcSample() throws Exception { public void testRawCcSample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(
new ExtractorFactory() { () ->
@Override new RawCcExtractor(
public Extractor create() {
return new RawCcExtractor(
Format.createTextContainerFormat( Format.createTextContainerFormat(
/* id= */ null, /* id= */ null,
/* label= */ null, /* label= */ null,
@ -46,9 +42,7 @@ public final class RawCcExtractorTest {
/* bitrate= */ Format.NO_VALUE, /* bitrate= */ Format.NO_VALUE,
/* selectionFlags= */ 0, /* selectionFlags= */ 0,
/* language= */ null, /* language= */ null,
/* accessibilityChannel= */ 1)); /* accessibilityChannel= */ 1)),
}
},
"rawcc/sample.rawcc"); "rawcc/sample.rawcc");
} }
} }

View File

@ -15,9 +15,7 @@
*/ */
package com.google.android.exoplayer2.extractor.ts; package com.google.android.exoplayer2.extractor.ts;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
@ -28,13 +26,6 @@ public final class Ac3ExtractorTest {
@Test @Test
public void testSample() throws Exception { public void testSample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(Ac3Extractor::new, "ts/sample.ac3");
new ExtractorFactory() {
@Override
public Extractor create() {
return new Ac3Extractor();
}
},
"ts/sample.ac3");
} }
} }

View File

@ -15,9 +15,7 @@
*/ */
package com.google.android.exoplayer2.extractor.ts; package com.google.android.exoplayer2.extractor.ts;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
@ -28,27 +26,16 @@ public final class AdtsExtractorTest {
@Test @Test
public void testSample() throws Exception { public void testSample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(AdtsExtractor::new, "ts/sample.adts");
new ExtractorFactory() {
@Override
public Extractor create() {
return new AdtsExtractor();
}
},
"ts/sample.adts");
} }
@Test @Test
public void testSample_withSeeking() throws Exception { public void testSample_withSeeking() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(
new ExtractorFactory() { () ->
@Override new AdtsExtractor(
public Extractor create() {
return new AdtsExtractor(
/* firstStreamSampleTimestampUs= */ 0, /* firstStreamSampleTimestampUs= */ 0,
/* flags= */ AdtsExtractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING); /* flags= */ AdtsExtractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING),
}
},
"ts/sample_cbs.adts"); "ts/sample_cbs.adts");
} }
} }

View File

@ -15,9 +15,7 @@
*/ */
package com.google.android.exoplayer2.extractor.ts; package com.google.android.exoplayer2.extractor.ts;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
@ -28,13 +26,6 @@ public final class PsExtractorTest {
@Test @Test
public void testSample() throws Exception { public void testSample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(PsExtractor::new, "ts/sample.ps");
new ExtractorFactory() {
@Override
public Extractor create() {
return new PsExtractor();
}
},
"ts/sample.ps");
} }
} }

View File

@ -27,7 +27,6 @@ import com.google.android.exoplayer2.extractor.TrackOutput;
import com.google.android.exoplayer2.extractor.ts.TsPayloadReader.EsInfo; import com.google.android.exoplayer2.extractor.ts.TsPayloadReader.EsInfo;
import com.google.android.exoplayer2.extractor.ts.TsPayloadReader.TrackIdGenerator; import com.google.android.exoplayer2.extractor.ts.TsPayloadReader.TrackIdGenerator;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import com.google.android.exoplayer2.testutil.FakeExtractorInput; import com.google.android.exoplayer2.testutil.FakeExtractorInput;
import com.google.android.exoplayer2.testutil.FakeExtractorOutput; import com.google.android.exoplayer2.testutil.FakeExtractorOutput;
import com.google.android.exoplayer2.testutil.FakeTrackOutput; import com.google.android.exoplayer2.testutil.FakeTrackOutput;
@ -50,14 +49,7 @@ public final class TsExtractorTest {
@Test @Test
public void testSample() throws Exception { public void testSample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(TsExtractor::new, "ts/sample.ts");
new ExtractorFactory() {
@Override
public Extractor create() {
return new TsExtractor();
}
},
"ts/sample.ts");
} }
@Test @Test
@ -82,15 +74,7 @@ public final class TsExtractorTest {
fileData = out.toByteArray(); fileData = out.toByteArray();
ExtractorAsserts.assertOutput( ExtractorAsserts.assertOutput(
new ExtractorFactory() { TsExtractor::new, "ts/sample.ts", fileData, RuntimeEnvironment.application);
@Override
public Extractor create() {
return new TsExtractor();
}
},
"ts/sample.ts",
fileData,
RuntimeEnvironment.application);
} }
@Test @Test

View File

@ -15,9 +15,7 @@
*/ */
package com.google.android.exoplayer2.extractor.wav; package com.google.android.exoplayer2.extractor.wav;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
import com.google.android.exoplayer2.testutil.ExtractorAsserts.ExtractorFactory;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
@ -28,13 +26,6 @@ public final class WavExtractorTest {
@Test @Test
public void testSample() throws Exception { public void testSample() throws Exception {
ExtractorAsserts.assertBehavior( ExtractorAsserts.assertBehavior(WavExtractor::new, "wav/sample.wav");
new ExtractorFactory() {
@Override
public Extractor create() {
return new WavExtractor();
}
},
"wav/sample.wav");
} }
} }

View File

@ -331,13 +331,7 @@ public class DownloadManagerTest {
remove2Action.post().assertStarted(); remove2Action.post().assertStarted();
download2Action.post().assertDoesNotStart(); download2Action.post().assertDoesNotStart();
runOnMainThread( runOnMainThread(() -> downloadManager.stopDownloads());
new Runnable() {
@Override
public void run() {
downloadManager.stopDownloads();
}
});
download1Action.assertStopped(); download1Action.assertStopped();
@ -354,13 +348,7 @@ public class DownloadManagerTest {
// New download actions can be added but they don't start. // New download actions can be added but they don't start.
download3Action.post().assertDoesNotStart(); download3Action.post().assertDoesNotStart();
runOnMainThread( runOnMainThread(() -> downloadManager.startDownloads());
new Runnable() {
@Override
public void run() {
downloadManager.startDownloads();
}
});
download2Action.assertStarted().unblock().assertCompleted(); download2Action.assertStarted().unblock().assertCompleted();
download3Action.assertStarted().unblock().assertCompleted(); download3Action.assertStarted().unblock().assertCompleted();
@ -380,24 +368,12 @@ public class DownloadManagerTest {
// download3Action doesn't start as DM was configured to run two downloads in parallel. // download3Action doesn't start as DM was configured to run two downloads in parallel.
download3Action.post().assertDoesNotStart(); download3Action.post().assertDoesNotStart();
runOnMainThread( runOnMainThread(() -> downloadManager.stopDownloads());
new Runnable() {
@Override
public void run() {
downloadManager.stopDownloads();
}
});
// download1Action doesn't stop yet as it ignores interrupts. // download1Action doesn't stop yet as it ignores interrupts.
download2Action.assertStopped(); download2Action.assertStopped();
runOnMainThread( runOnMainThread(() -> downloadManager.startDownloads());
new Runnable() {
@Override
public void run() {
downloadManager.startDownloads();
}
});
// download2Action starts immediately. // download2Action starts immediately.
download2Action.assertStarted(); download2Action.assertStarted();
@ -421,9 +397,7 @@ public class DownloadManagerTest {
} }
try { try {
runOnMainThread( runOnMainThread(
new Runnable() { () -> {
@Override
public void run() {
downloadManager = downloadManager =
new DownloadManager( new DownloadManager(
new DownloaderConstructorHelper( new DownloaderConstructorHelper(
@ -436,7 +410,6 @@ public class DownloadManagerTest {
new TestDownloadManagerListener(downloadManager, dummyMainThread); new TestDownloadManagerListener(downloadManager, dummyMainThread);
downloadManager.addListener(downloadManagerListener); downloadManager.addListener(downloadManagerListener);
downloadManager.startDownloads(); downloadManager.startDownloads();
}
}); });
} catch (Throwable throwable) { } catch (Throwable throwable) {
throw new Exception(throwable); throw new Exception(throwable);
@ -445,13 +418,7 @@ public class DownloadManagerTest {
private void releaseDownloadManager() throws Exception { private void releaseDownloadManager() throws Exception {
try { try {
runOnMainThread( runOnMainThread(() -> downloadManager.release());
new Runnable() {
@Override
public void run() {
downloadManager.release();
}
});
} catch (Throwable throwable) { } catch (Throwable throwable) {
throw new Exception(throwable); throw new Exception(throwable);
} }
@ -519,13 +486,7 @@ public class DownloadManagerTest {
} }
private FakeDownloadAction post() { private FakeDownloadAction post() {
runOnMainThread( runOnMainThread(() -> downloadManager.handleAction(FakeDownloadAction.this));
new Runnable() {
@Override
public void run() {
downloadManager.handleAction(FakeDownloadAction.this);
}
});
return this; return this;
} }

View File

@ -501,9 +501,7 @@ public final class ClippingMediaSourceTest {
final MediaLoadData[] reportedMediaLoadData = new MediaLoadData[1]; final MediaLoadData[] reportedMediaLoadData = new MediaLoadData[1];
try { try {
testRunner.runOnPlaybackThread( testRunner.runOnPlaybackThread(
new Runnable() { () ->
@Override
public void run() {
clippingMediaSource.addEventListener( clippingMediaSource.addEventListener(
new Handler(), new Handler(),
new DefaultMediaSourceEventListener() { new DefaultMediaSourceEventListener() {
@ -514,9 +512,7 @@ public final class ClippingMediaSourceTest {
MediaLoadData mediaLoadData) { MediaLoadData mediaLoadData) {
reportedMediaLoadData[0] = mediaLoadData; reportedMediaLoadData[0] = mediaLoadData;
} }
}); }));
}
});
testRunner.prepareSource(); testRunner.prepareSource();
// Create period to send the test event configured above. // Create period to send the test event configured above.
testRunner.createPeriod( testRunner.createPeriod(

View File

@ -247,12 +247,7 @@ public final class ConcatenatingMediaSourceTest {
// Trigger source info refresh for lazy source and check that the timeline now contains all // Trigger source info refresh for lazy source and check that the timeline now contains all
// information for all windows. // information for all windows.
testRunner.runOnPlaybackThread( testRunner.runOnPlaybackThread(
new Runnable() { () -> lazySources[1].setNewSourceInfo(createFakeTimeline(8), null));
@Override
public void run() {
lazySources[1].setNewSourceInfo(createFakeTimeline(8), null);
}
});
timeline = testRunner.assertTimelineChangeBlocking(); timeline = testRunner.assertTimelineChangeBlocking();
TimelineAsserts.assertPeriodCounts(timeline, 1, 9); TimelineAsserts.assertPeriodCounts(timeline, 1, 9);
TimelineAsserts.assertWindowTags(timeline, 111, 999); TimelineAsserts.assertWindowTags(timeline, 111, 999);
@ -292,12 +287,7 @@ public final class ConcatenatingMediaSourceTest {
// Trigger source info refresh for lazy media source. Assert that now all information is // Trigger source info refresh for lazy media source. Assert that now all information is
// available again and the previously created period now also finished preparing. // available again and the previously created period now also finished preparing.
testRunner.runOnPlaybackThread( testRunner.runOnPlaybackThread(
new Runnable() { () -> lazySources[3].setNewSourceInfo(createFakeTimeline(7), null));
@Override
public void run() {
lazySources[3].setNewSourceInfo(createFakeTimeline(7), null);
}
});
timeline = testRunner.assertTimelineChangeBlocking(); timeline = testRunner.assertTimelineChangeBlocking();
TimelineAsserts.assertPeriodCounts(timeline, 8, 1, 2, 9); TimelineAsserts.assertPeriodCounts(timeline, 8, 1, 2, 9);
TimelineAsserts.assertWindowTags(timeline, 888, 111, 222, 999); TimelineAsserts.assertWindowTags(timeline, 888, 111, 222, 999);
@ -484,12 +474,7 @@ public final class ConcatenatingMediaSourceTest {
testRunner.prepareSource(); testRunner.prepareSource();
final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner); final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () -> mediaSource.addMediaSource(createFakeMediaSource(), timelineGrabber));
@Override
public void run() {
mediaSource.addMediaSource(createFakeMediaSource(), timelineGrabber);
}
});
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertThat(timeline.getWindowCount()).isEqualTo(1); assertThat(timeline.getWindowCount()).isEqualTo(1);
} finally { } finally {
@ -504,15 +489,11 @@ public final class ConcatenatingMediaSourceTest {
testRunner.prepareSource(); testRunner.prepareSource();
final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner); final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () ->
@Override
public void run() {
mediaSource.addMediaSources( mediaSource.addMediaSources(
Arrays.asList( Arrays.asList(
new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}), new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}),
timelineGrabber); timelineGrabber));
}
});
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertThat(timeline.getWindowCount()).isEqualTo(2); assertThat(timeline.getWindowCount()).isEqualTo(2);
} finally { } finally {
@ -527,12 +508,8 @@ public final class ConcatenatingMediaSourceTest {
testRunner.prepareSource(); testRunner.prepareSource();
final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner); final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () ->
@Override mediaSource.addMediaSource(/* index */ 0, createFakeMediaSource(), timelineGrabber));
public void run() {
mediaSource.addMediaSource(/* index */ 0, createFakeMediaSource(), timelineGrabber);
}
});
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertThat(timeline.getWindowCount()).isEqualTo(1); assertThat(timeline.getWindowCount()).isEqualTo(1);
} finally { } finally {
@ -547,16 +524,12 @@ public final class ConcatenatingMediaSourceTest {
testRunner.prepareSource(); testRunner.prepareSource();
final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner); final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () ->
@Override
public void run() {
mediaSource.addMediaSources( mediaSource.addMediaSources(
/* index */ 0, /* index */ 0,
Arrays.asList( Arrays.asList(
new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}), new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}),
timelineGrabber); timelineGrabber));
}
});
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertThat(timeline.getWindowCount()).isEqualTo(2); assertThat(timeline.getWindowCount()).isEqualTo(2);
} finally { } finally {
@ -569,23 +542,12 @@ public final class ConcatenatingMediaSourceTest {
DummyMainThread dummyMainThread = new DummyMainThread(); DummyMainThread dummyMainThread = new DummyMainThread();
try { try {
testRunner.prepareSource(); testRunner.prepareSource();
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(() -> mediaSource.addMediaSource(createFakeMediaSource()));
new Runnable() {
@Override
public void run() {
mediaSource.addMediaSource(createFakeMediaSource());
}
});
testRunner.assertTimelineChangeBlocking(); testRunner.assertTimelineChangeBlocking();
final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner); final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () -> mediaSource.removeMediaSource(/* index */ 0, timelineGrabber));
@Override
public void run() {
mediaSource.removeMediaSource(/* index */ 0, timelineGrabber);
}
});
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertThat(timeline.getWindowCount()).isEqualTo(0); assertThat(timeline.getWindowCount()).isEqualTo(0);
} finally { } finally {
@ -599,24 +561,15 @@ public final class ConcatenatingMediaSourceTest {
try { try {
testRunner.prepareSource(); testRunner.prepareSource();
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () ->
@Override
public void run() {
mediaSource.addMediaSources( mediaSource.addMediaSources(
Arrays.asList( Arrays.asList(
new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()})); new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()})));
}
});
testRunner.assertTimelineChangeBlocking(); testRunner.assertTimelineChangeBlocking();
final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner); final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () -> mediaSource.moveMediaSource(/* fromIndex */ 1, /* toIndex */ 0, timelineGrabber));
@Override
public void run() {
mediaSource.moveMediaSource(/* fromIndex */ 1, /* toIndex */ 0, timelineGrabber);
}
});
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertThat(timeline.getWindowCount()).isEqualTo(2); assertThat(timeline.getWindowCount()).isEqualTo(2);
} finally { } finally {
@ -849,23 +802,14 @@ public final class ConcatenatingMediaSourceTest {
final FakeMediaSource unpreparedChildSource = final FakeMediaSource unpreparedChildSource =
new FakeMediaSource(/* timeline= */ null, /* manifest= */ null); new FakeMediaSource(/* timeline= */ null, /* manifest= */ null);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () -> {
@Override
public void run() {
mediaSource.addMediaSource(preparedChildSource); mediaSource.addMediaSource(preparedChildSource);
mediaSource.addMediaSource(unpreparedChildSource); mediaSource.addMediaSource(unpreparedChildSource);
}
}); });
testRunner.prepareSource(); testRunner.prepareSource();
final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner); final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(() -> mediaSource.clear(timelineGrabber));
new Runnable() {
@Override
public void run() {
mediaSource.clear(timelineGrabber);
}
});
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertThat(timeline.isEmpty()).isTrue(); assertThat(timeline.isEmpty()).isTrue();

View File

@ -60,13 +60,7 @@ public final class CacheDataSourceTest {
testDataUri = Uri.parse("test_data"); testDataUri = Uri.parse("test_data");
fixedCacheKey = CacheUtil.generateKey(testDataUri); fixedCacheKey = CacheUtil.generateKey(testDataUri);
expectedCacheKey = fixedCacheKey; expectedCacheKey = fixedCacheKey;
cacheKeyFactory = cacheKeyFactory = dataSpec -> CACHE_KEY_PREFIX + "." + CacheUtil.generateKey(dataSpec.uri);
new CacheKeyFactory() {
@Override
public String buildCacheKey(DataSpec dataSpec) {
return CACHE_KEY_PREFIX + "." + CacheUtil.generateKey(dataSpec.uri);
}
};
tempFolder = Util.createTempDirectory(RuntimeEnvironment.application, "ExoPlayerTest"); tempFolder = Util.createTempDirectory(RuntimeEnvironment.application, "ExoPlayerTest");
cache = new SimpleCache(tempFolder, new NoOpCacheEvictor()); cache = new SimpleCache(tempFolder, new NoOpCacheEvictor());
} }
@ -366,13 +360,7 @@ public final class CacheDataSourceTest {
// Insert an action just before the end of the data to fail the test if reading from upstream // Insert an action just before the end of the data to fail the test if reading from upstream
// reaches end of the data. // reaches end of the data.
fakeData fakeData
.appendReadAction( .appendReadAction(() -> fail("Read from upstream shouldn't reach to the end of the data."))
new Runnable() {
@Override
public void run() {
fail("Read from upstream shouldn't reach to the end of the data.");
}
})
.appendReadData(1); .appendReadData(1);
// Create cache read-only CacheDataSource. // Create cache read-only CacheDataSource.
CacheDataSource cacheDataSource = CacheDataSource cacheDataSource =
@ -408,13 +396,7 @@ public final class CacheDataSourceTest {
// Insert an action just before the end of the data to fail the test if reading from upstream // Insert an action just before the end of the data to fail the test if reading from upstream
// reaches end of the data. // reaches end of the data.
fakeData fakeData
.appendReadAction( .appendReadAction(() -> fail("Read from upstream shouldn't reach to the end of the data."))
new Runnable() {
@Override
public void run() {
fail("Read from upstream shouldn't reach to the end of the data.");
}
})
.appendReadData(1); .appendReadData(1);
// Lock the content on the cache. // Lock the content on the cache.

View File

@ -292,22 +292,15 @@ public final class CacheUtilTest {
@Test @Test
public void testCachePolling() throws Exception { public void testCachePolling() throws Exception {
final CachingCounters counters = new CachingCounters(); final CachingCounters counters = new CachingCounters();
FakeDataSet fakeDataSet = new FakeDataSet().newData("test_data") FakeDataSet fakeDataSet =
new FakeDataSet()
.newData("test_data")
.appendReadData(TestUtil.buildTestData(100)) .appendReadData(TestUtil.buildTestData(100))
.appendReadAction(new Runnable() { .appendReadAction(() -> assertCounters(counters, 0, 100, 300))
@Override
public void run() {
assertCounters(counters, 0, 100, 300);
}
})
.appendReadData(TestUtil.buildTestData(100)) .appendReadData(TestUtil.buildTestData(100))
.appendReadAction(new Runnable() { .appendReadAction(() -> assertCounters(counters, 0, 200, 300))
@Override .appendReadData(TestUtil.buildTestData(100))
public void run() { .endData();
assertCounters(counters, 0, 200, 300);
}
})
.appendReadData(TestUtil.buildTestData(100)).endData();
FakeDataSource dataSource = new FakeDataSource(fakeDataSet); FakeDataSource dataSource = new FakeDataSource(fakeDataSet);
CacheUtil.cache( CacheUtil.cache(

View File

@ -37,8 +37,6 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
@ -259,12 +257,12 @@ public class SimpleCacheTest {
addCache(simpleCache, KEY_1, 0, 15); addCache(simpleCache, KEY_1, 0, 15);
// Make index.store() throw exception from now on. // Make index.store() throw exception from now on.
doAnswer(new Answer<Object>() { doAnswer(
@Override invocation -> {
public Object answer(InvocationOnMock invocation) throws Throwable { throw new CacheException("SimpleCacheTest");
throw new Cache.CacheException("SimpleCacheTest"); })
} .when(index)
}).when(index).store(); .store();
// Adding more content will make LeastRecentlyUsedCacheEvictor evict previous content. // Adding more content will make LeastRecentlyUsedCacheEvictor evict previous content.
try { try {

View File

@ -589,18 +589,8 @@ public final class DashMediaSource extends BaseMediaSource {
} else { } else {
manifestCallback = new ManifestCallback(); manifestCallback = new ManifestCallback();
manifestLoadErrorThrower = new ManifestLoadErrorThrower(); manifestLoadErrorThrower = new ManifestLoadErrorThrower();
refreshManifestRunnable = new Runnable() { refreshManifestRunnable = this::startLoadingManifest;
@Override simulateManifestRefreshRunnable = () -> processManifest(false);
public void run() {
startLoadingManifest();
}
};
simulateManifestRefreshRunnable = new Runnable() {
@Override
public void run() {
processManifest(false);
}
};
} }
} }

View File

@ -110,10 +110,7 @@ public class DownloadManagerDashTest {
fakeDataSet fakeDataSet
.newData(TEST_MPD_URI) .newData(TEST_MPD_URI)
.appendReadAction( .appendReadAction(
new Runnable() { () -> {
@SuppressWarnings("InfiniteLoopStatement")
@Override
public void run() {
try { try {
// Wait until interrupted. // Wait until interrupted.
while (true) { while (true) {
@ -122,7 +119,6 @@ public class DownloadManagerDashTest {
} catch (InterruptedException ignored) { } catch (InterruptedException ignored) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
}
}) })
.appendReadData(TEST_MPD) .appendReadData(TEST_MPD)
.endData(); .endData();
@ -130,13 +126,10 @@ public class DownloadManagerDashTest {
// Run DM accessing code on UI/main thread as it should be. Also not to block handling of loaded // Run DM accessing code on UI/main thread as it should be. Also not to block handling of loaded
// actions. // actions.
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () -> {
@Override
public void run() {
// Setup an Action and immediately release the DM. // Setup an Action and immediately release the DM.
handleDownloadAction(fakeStreamKey1, fakeStreamKey2); handleDownloadAction(fakeStreamKey1, fakeStreamKey2);
downloadManager.release(); downloadManager.release();
}
}); });
assertThat(actionFile.exists()).isTrue(); assertThat(actionFile.exists()).isTrue();
@ -146,13 +139,7 @@ public class DownloadManagerDashTest {
// Revert fakeDataSet to normal. // Revert fakeDataSet to normal.
fakeDataSet.setData(TEST_MPD_URI, TEST_MPD); fakeDataSet.setData(TEST_MPD_URI, TEST_MPD);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(this::createDownloadManager);
new Runnable() {
@Override
public void run() {
createDownloadManager();
}
});
// Block on the test thread. // Block on the test thread.
blockUntilTasksCompleteAndThrowAnyDownloadError(); blockUntilTasksCompleteAndThrowAnyDownloadError();
@ -178,13 +165,7 @@ public class DownloadManagerDashTest {
public void testHandleInterferingDownloadAction() throws Throwable { public void testHandleInterferingDownloadAction() throws Throwable {
fakeDataSet fakeDataSet
.newData("audio_segment_2") .newData("audio_segment_2")
.appendReadAction( .appendReadAction(() -> handleDownloadAction(fakeStreamKey2))
new Runnable() {
@Override
public void run() {
handleDownloadAction(fakeStreamKey2);
}
})
.appendReadData(TestUtil.buildTestData(5)) .appendReadData(TestUtil.buildTestData(5))
.endData(); .endData();
@ -224,13 +205,7 @@ public class DownloadManagerDashTest {
final ConditionVariable downloadInProgressCondition = new ConditionVariable(); final ConditionVariable downloadInProgressCondition = new ConditionVariable();
fakeDataSet fakeDataSet
.newData("audio_segment_2") .newData("audio_segment_2")
.appendReadAction( .appendReadAction(downloadInProgressCondition::open)
new Runnable() {
@Override
public void run() {
downloadInProgressCondition.open();
}
})
.appendReadData(TestUtil.buildTestData(5)) .appendReadData(TestUtil.buildTestData(5))
.endData(); .endData();
@ -259,9 +234,7 @@ public class DownloadManagerDashTest {
private void createDownloadManager() { private void createDownloadManager() {
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () -> {
@Override
public void run() {
Factory fakeDataSourceFactory = Factory fakeDataSourceFactory =
new FakeDataSource.Factory(null).setFakeDataSet(fakeDataSet); new FakeDataSource.Factory(null).setFakeDataSet(fakeDataSet);
downloadManager = downloadManager =
@ -276,7 +249,6 @@ public class DownloadManagerDashTest {
new TestDownloadManagerListener(downloadManager, dummyMainThread); new TestDownloadManagerListener(downloadManager, dummyMainThread);
downloadManager.addListener(downloadManagerListener); downloadManager.addListener(downloadManagerListener);
downloadManager.startDownloads(); downloadManager.startDownloads();
}
}); });
} }

View File

@ -78,9 +78,7 @@ public class DownloadServiceDashTest {
cache = new SimpleCache(tempFolder, new NoOpCacheEvictor()); cache = new SimpleCache(tempFolder, new NoOpCacheEvictor());
Runnable pauseAction = Runnable pauseAction =
new Runnable() { () -> {
@Override
public void run() {
if (pauseDownloadCondition != null) { if (pauseDownloadCondition != null) {
try { try {
pauseDownloadCondition.block(); pauseDownloadCondition.block();
@ -88,7 +86,6 @@ public class DownloadServiceDashTest {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
}
}; };
fakeDataSet = fakeDataSet =
new FakeDataSet() new FakeDataSet()
@ -109,9 +106,7 @@ public class DownloadServiceDashTest {
fakeStreamKey2 = new StreamKey(0, 1, 0); fakeStreamKey2 = new StreamKey(0, 1, 0);
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () -> {
@Override
public void run() {
File actionFile; File actionFile;
try { try {
actionFile = Util.createTempFile(context, "ExoPlayerTest"); actionFile = Util.createTempFile(context, "ExoPlayerTest");
@ -145,19 +140,12 @@ public class DownloadServiceDashTest {
} }
}; };
dashDownloadService.onCreate(); dashDownloadService.onCreate();
}
}); });
} }
@After @After
public void tearDown() { public void tearDown() {
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(() -> dashDownloadService.onDestroy());
new Runnable() {
@Override
public void run() {
dashDownloadService.onDestroy();
}
});
Util.recursiveDelete(tempFolder); Util.recursiveDelete(tempFolder);
dummyMainThread.release(); dummyMainThread.release();
} }
@ -210,13 +198,10 @@ public class DownloadServiceDashTest {
private void callDownloadServiceOnStart(final DownloadAction action) { private void callDownloadServiceOnStart(final DownloadAction action) {
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () -> {
@Override
public void run() {
Intent startIntent = Intent startIntent =
DownloadService.buildAddActionIntent(context, DownloadService.class, action, false); DownloadService.buildAddActionIntent(context, DownloadService.class, action, false);
dashDownloadService.onStartCommand(startIntent, 0, 0); dashDownloadService.onStartCommand(startIntent, 0, 0);
}
}); });
} }

View File

@ -684,12 +684,7 @@ public final class SsMediaSource extends BaseMediaSource
} }
long nextLoadTimestamp = manifestLoadStartTimestamp + MINIMUM_MANIFEST_REFRESH_PERIOD_MS; long nextLoadTimestamp = manifestLoadStartTimestamp + MINIMUM_MANIFEST_REFRESH_PERIOD_MS;
long delayUntilNextLoad = Math.max(0, nextLoadTimestamp - SystemClock.elapsedRealtime()); long delayUntilNextLoad = Math.max(0, nextLoadTimestamp - SystemClock.elapsedRealtime());
manifestRefreshHandler.postDelayed(new Runnable() { manifestRefreshHandler.postDelayed(this::startLoadingManifest, delayUntilNextLoad);
@Override
public void run() {
startLoadingManifest();
}
}, delayUntilNextLoad);
} }
private void startLoadingManifest() { private void startLoadingManifest() {

View File

@ -208,6 +208,8 @@ public class PlayerControlView extends FrameLayout {
private final Formatter formatter; private final Formatter formatter;
private final Timeline.Period period; private final Timeline.Period period;
private final Timeline.Window window; private final Timeline.Window window;
private final Runnable updateProgressAction;
private final Runnable hideAction;
private final Drawable repeatOffButtonDrawable; private final Drawable repeatOffButtonDrawable;
private final Drawable repeatOneButtonDrawable; private final Drawable repeatOneButtonDrawable;
@ -236,22 +238,6 @@ public class PlayerControlView extends FrameLayout {
private long[] extraAdGroupTimesMs; private long[] extraAdGroupTimesMs;
private boolean[] extraPlayedAdGroups; private boolean[] extraPlayedAdGroups;
private final Runnable updateProgressAction =
new Runnable() {
@Override
public void run() {
updateProgress();
}
};
private final Runnable hideAction =
new Runnable() {
@Override
public void run() {
hide();
}
};
public PlayerControlView(Context context) { public PlayerControlView(Context context) {
this(context, null); this(context, null);
} }
@ -303,6 +289,8 @@ public class PlayerControlView extends FrameLayout {
extraPlayedAdGroups = new boolean[0]; extraPlayedAdGroups = new boolean[0];
componentListener = new ComponentListener(); componentListener = new ComponentListener();
controlDispatcher = new com.google.android.exoplayer2.DefaultControlDispatcher(); controlDispatcher = new com.google.android.exoplayer2.DefaultControlDispatcher();
updateProgressAction = this::updateProgress;
hideAction = this::hide;
LayoutInflater.from(context).inflate(controllerLayoutId, this); LayoutInflater.from(context).inflate(controllerLayoutId, this);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);

View File

@ -203,15 +203,12 @@ public class PlayerNotificationManager {
public void onBitmap(final Bitmap bitmap) { public void onBitmap(final Bitmap bitmap) {
if (bitmap != null) { if (bitmap != null) {
mainHandler.post( mainHandler.post(
new Runnable() { () -> {
@Override
public void run() {
if (player != null if (player != null
&& notificationTag == currentNotificationTag && notificationTag == currentNotificationTag
&& isNotificationStarted) { && isNotificationStarted) {
updateNotification(bitmap); updateNotification(bitmap);
} }
}
}); });
} }
} }

View File

@ -19,7 +19,6 @@ import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.app.Dialog; import android.app.Dialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray; import android.content.res.TypedArray;
import android.support.annotation.AttrRes; import android.support.annotation.AttrRes;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
@ -80,13 +79,7 @@ public class TrackSelectionView extends LinearLayout {
final TrackSelectionView selectionView = dialogView.findViewById(R.id.exo_track_selection_view); final TrackSelectionView selectionView = dialogView.findViewById(R.id.exo_track_selection_view);
selectionView.init(trackSelector, rendererIndex); selectionView.init(trackSelector, rendererIndex);
Dialog.OnClickListener okClickListener = Dialog.OnClickListener okClickListener = (dialog, which) -> selectionView.applySelection();
new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectionView.applySelection();
}
};
AlertDialog dialog = AlertDialog dialog =
builder builder

View File

@ -469,12 +469,8 @@ public abstract class Action {
SimpleExoPlayer player, DefaultTrackSelector trackSelector, Surface surface) { SimpleExoPlayer player, DefaultTrackSelector trackSelector, Surface surface) {
player player
.createMessage( .createMessage(
new Target() { (messageType, payload) -> {
@Override
public void handleMessage(int messageType, Object payload)
throws ExoPlaybackException {
throw exception; throw exception;
}
}) })
.send(); .send();
} }
@ -510,25 +506,14 @@ public abstract class Action {
// Schedule one message on the playback thread to pause the player immediately. // Schedule one message on the playback thread to pause the player immediately.
player player
.createMessage( .createMessage(
new Target() { (messageType, payload) -> player.setPlayWhenReady(/* playWhenReady= */ false))
@Override
public void handleMessage(int messageType, Object payload)
throws ExoPlaybackException {
player.setPlayWhenReady(/* playWhenReady= */ false);
}
})
.setPosition(windowIndex, positionMs) .setPosition(windowIndex, positionMs)
.send(); .send();
// Schedule another message on this test thread to continue action schedule. // Schedule another message on this test thread to continue action schedule.
player player
.createMessage( .createMessage(
new Target() { (messageType, payload) ->
@Override nextAction.schedule(player, trackSelector, surface, handler))
public void handleMessage(int messageType, Object payload)
throws ExoPlaybackException {
nextAction.schedule(player, trackSelector, surface, handler);
}
})
.setPosition(windowIndex, positionMs) .setPosition(windowIndex, positionMs)
.setHandler(new Handler()) .setHandler(new Handler())
.send(); .send();

View File

@ -610,13 +610,7 @@ public final class ActionSchedule {
ActionNode nextAction) { ActionNode nextAction) {
Assertions.checkArgument(nextAction == null); Assertions.checkArgument(nextAction == null);
if (callback != null) { if (callback != null) {
handler.post( handler.post(() -> callback.onActionScheduleFinished());
new Runnable() {
@Override
public void run() {
callback.onActionScheduleFinished();
}
});
} }
} }

View File

@ -60,12 +60,9 @@ public final class DummyMainThread {
} else { } else {
final ConditionVariable finishedCondition = new ConditionVariable(); final ConditionVariable finishedCondition = new ConditionVariable();
handler.post( handler.post(
new Runnable() { () -> {
@Override
public void run() {
runnable.run(); runnable.run();
finishedCondition.open(); finishedCondition.open();
}
}); });
assertThat(finishedCondition.block(timeoutMs)).isTrue(); assertThat(finishedCondition.block(timeoutMs)).isTrue();
} }

View File

@ -344,12 +344,7 @@ public abstract class ExoHostedTest
player = null; player = null;
// We post opening of the finished condition so that any events posted to the main thread as a // We post opening of the finished condition so that any events posted to the main thread as a
// result of player.release() are guaranteed to be handled before the test returns. // result of player.release() are guaranteed to be handled before the test returns.
actionHandler.post(new Runnable() { actionHandler.post(testFinished::open);
@Override
public void run() {
testFinished.open();
}
});
return true; return true;
} }

View File

@ -33,12 +33,8 @@ import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.analytics.AnalyticsCollector; import com.google.android.exoplayer2.analytics.AnalyticsCollector;
import com.google.android.exoplayer2.analytics.AnalyticsListener; import com.google.android.exoplayer2.analytics.AnalyticsListener;
import com.google.android.exoplayer2.audio.AudioRendererEventListener; import com.google.android.exoplayer2.audio.AudioRendererEventListener;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
import com.google.android.exoplayer2.metadata.MetadataOutput;
import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.text.TextOutput;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelector;
@ -307,18 +303,12 @@ public final class ExoPlayerTestRunner implements Player.EventListener, ActionSc
renderers = new Renderer[] {new FakeRenderer(supportedFormats)}; renderers = new Renderer[] {new FakeRenderer(supportedFormats)};
} }
renderersFactory = renderersFactory =
new RenderersFactory() { (eventHandler,
@Override videoRendererEventListener,
public Renderer[] createRenderers( audioRendererEventListener,
android.os.Handler eventHandler, textRendererOutput,
VideoRendererEventListener videoRendererEventListener, metadataRendererOutput,
AudioRendererEventListener audioRendererEventListener, drmSessionManager) -> renderers;
TextOutput textRendererOutput,
MetadataOutput metadataRendererOutput,
DrmSessionManager<FrameworkMediaCrypto> drmSessionManager) {
return renderers;
}
};
} }
if (loadControl == null) { if (loadControl == null) {
loadControl = new DefaultLoadControl(); loadControl = new DefaultLoadControl();
@ -425,9 +415,7 @@ public final class ExoPlayerTestRunner implements Player.EventListener, ActionSc
*/ */
public ExoPlayerTestRunner start() { public ExoPlayerTestRunner start() {
handler.post( handler.post(
new Runnable() { () -> {
@Override
public void run() {
try { try {
player = player =
new TestSimpleExoPlayer( new TestSimpleExoPlayer(
@ -447,14 +435,12 @@ public final class ExoPlayerTestRunner implements Player.EventListener, ActionSc
} }
player.setPlayWhenReady(true); player.setPlayWhenReady(true);
if (actionSchedule != null) { if (actionSchedule != null) {
actionSchedule.start( actionSchedule.start(player, trackSelector, null, handler, ExoPlayerTestRunner.this);
player, trackSelector, null, handler, ExoPlayerTestRunner.this);
} }
player.prepare(mediaSource); player.prepare(mediaSource);
} catch (Exception e) { } catch (Exception e) {
handleException(e); handleException(e);
} }
}
}); });
return this; return this;
} }
@ -579,9 +565,8 @@ public final class ExoPlayerTestRunner implements Player.EventListener, ActionSc
// Private implementation details. // Private implementation details.
private void release() throws InterruptedException { private void release() throws InterruptedException {
handler.post(new Runnable() { handler.post(
@Override () -> {
public void run() {
try { try {
if (player != null) { if (player != null) {
player.release(); player.release();
@ -591,7 +576,6 @@ public final class ExoPlayerTestRunner implements Player.EventListener, ActionSc
} finally { } finally {
playerThread.quit(); playerThread.quit();
} }
}
}); });
playerThread.join(); playerThread.join();
} }

View File

@ -93,13 +93,7 @@ public class FakeMediaPeriod implements MediaPeriod {
public synchronized void setPreparationComplete() { public synchronized void setPreparationComplete() {
deferOnPrepared = false; deferOnPrepared = false;
if (playerHandler != null && prepareCallback != null) { if (playerHandler != null && prepareCallback != null) {
playerHandler.post( playerHandler.post(this::finishPreparation);
new Runnable() {
@Override
public void run() {
finishPreparation();
}
});
} }
} }

View File

@ -149,15 +149,12 @@ public class FakeMediaSource extends BaseMediaSource {
public synchronized void setNewSourceInfo(final Timeline newTimeline, final Object newManifest) { public synchronized void setNewSourceInfo(final Timeline newTimeline, final Object newManifest) {
if (sourceInfoRefreshHandler != null) { if (sourceInfoRefreshHandler != null) {
sourceInfoRefreshHandler.post( sourceInfoRefreshHandler.post(
new Runnable() { () -> {
@Override
public void run() {
assertThat(releasedSource).isFalse(); assertThat(releasedSource).isFalse();
assertThat(preparedSource).isTrue(); assertThat(preparedSource).isTrue();
timeline = newTimeline; timeline = newTimeline;
manifest = newManifest; manifest = newManifest;
finishSourcePreparation(); finishSourcePreparation();
}
}); });
} else { } else {
timeline = newTimeline; timeline = newTimeline;

View File

@ -118,12 +118,10 @@ public final class HostActivity extends Activity implements SurfaceHolder.Callba
forcedStopped = false; forcedStopped = false;
hostedTestStarted = false; hostedTestStarted = false;
runOnUiThread(new Runnable() { runOnUiThread(
@Override () -> {
public void run() {
HostActivity.this.hostedTest = hostedTest; HostActivity.this.hostedTest = hostedTest;
maybeStartHostedTest(); maybeStartHostedTest();
}
}); });
if (!hostedTestStartedCondition.block(START_TIMEOUT_MS)) { if (!hostedTestStartedCondition.block(START_TIMEOUT_MS)) {
@ -145,12 +143,7 @@ public final class HostActivity extends Activity implements SurfaceHolder.Callba
fail(message); fail(message);
} }
} else { } else {
runOnUiThread(new Runnable() { runOnUiThread(hostedTest::forceStop);
@Override
public void run() {
hostedTest.forceStop();
}
});
String message = "Test timed out after " + timeoutMs + " ms."; String message = "Test timed out after " + timeoutMs + " ms.";
Log.e(TAG, message); Log.e(TAG, message);
if (failOnTimeout) { if (failOnTimeout) {

View File

@ -131,13 +131,7 @@ public final class FakeClockTest {
private static void waitForHandler(HandlerWrapper handler) { private static void waitForHandler(HandlerWrapper handler) {
final ConditionVariable handlerFinished = new ConditionVariable(); final ConditionVariable handlerFinished = new ConditionVariable();
handler.post( handler.post(handlerFinished::open);
new Runnable() {
@Override
public void run() {
handlerFinished.open();
}
});
handlerFinished.block(); handlerFinished.block();
} }

View File

@ -65,11 +65,8 @@ public final class FakeDataSetTest {
public void testSegmentTypes() { public void testSegmentTypes() {
byte[] testData = TestUtil.buildTestData(3); byte[] testData = TestUtil.buildTestData(3);
Runnable runnable = Runnable runnable =
new Runnable() { () -> {
@Override
public void run() {
// Do nothing. // Do nothing.
}
}; };
IOException exception = new IOException(); IOException exception = new IOException();
FakeDataSet fakeDataSet = FakeDataSet fakeDataSet =

View File

@ -97,9 +97,7 @@ public class MediaSourceTestRunner {
final Throwable[] throwable = new Throwable[1]; final Throwable[] throwable = new Throwable[1];
final ConditionVariable finishedCondition = new ConditionVariable(); final ConditionVariable finishedCondition = new ConditionVariable();
playbackHandler.post( playbackHandler.post(
new Runnable() { () -> {
@Override
public void run() {
try { try {
runnable.run(); runnable.run();
} catch (Throwable e) { } catch (Throwable e) {
@ -107,7 +105,6 @@ public class MediaSourceTestRunner {
} finally { } finally {
finishedCondition.open(); finishedCondition.open();
} }
}
}); });
assertThat(finishedCondition.block(TIMEOUT_MS)).isTrue(); assertThat(finishedCondition.block(TIMEOUT_MS)).isTrue();
if (throwable[0] != null) { if (throwable[0] != null) {
@ -123,9 +120,7 @@ public class MediaSourceTestRunner {
public Timeline prepareSource() throws IOException { public Timeline prepareSource() throws IOException {
final IOException[] prepareError = new IOException[1]; final IOException[] prepareError = new IOException[1];
runOnPlaybackThread( runOnPlaybackThread(
new Runnable() { () -> {
@Override
public void run() {
mediaSource.prepareSource( mediaSource.prepareSource(
player, player,
/* isTopLevelSource= */ true, /* isTopLevelSource= */ true,
@ -139,7 +134,6 @@ public class MediaSourceTestRunner {
} catch (IOException e) { } catch (IOException e) {
prepareError[0] = e; prepareError[0] = e;
} }
}
}); });
if (prepareError[0] != null) { if (prepareError[0] != null) {
throw prepareError[0]; throw prepareError[0];
@ -156,13 +150,7 @@ public class MediaSourceTestRunner {
*/ */
public MediaPeriod createPeriod(final MediaPeriodId periodId) { public MediaPeriod createPeriod(final MediaPeriodId periodId) {
final MediaPeriod[] holder = new MediaPeriod[1]; final MediaPeriod[] holder = new MediaPeriod[1];
runOnPlaybackThread( runOnPlaybackThread(() -> holder[0] = mediaSource.createPeriod(periodId, allocator));
new Runnable() {
@Override
public void run() {
holder[0] = mediaSource.createPeriod(periodId, allocator);
}
});
assertThat(holder[0]).isNotNull(); assertThat(holder[0]).isNotNull();
return holder[0]; return holder[0];
} }
@ -179,13 +167,11 @@ public class MediaSourceTestRunner {
final ConditionVariable prepareCalled = new ConditionVariable(); final ConditionVariable prepareCalled = new ConditionVariable();
final CountDownLatch preparedCountDown = new CountDownLatch(1); final CountDownLatch preparedCountDown = new CountDownLatch(1);
runOnPlaybackThread( runOnPlaybackThread(
new Runnable() { () -> {
@Override
public void run() {
mediaPeriod.prepare( mediaPeriod.prepare(
new MediaPeriod.Callback() { new MediaPeriod.Callback() {
@Override @Override
public void onPrepared(MediaPeriod mediaPeriod) { public void onPrepared(MediaPeriod mediaPeriod1) {
preparedCountDown.countDown(); preparedCountDown.countDown();
} }
@ -196,7 +182,6 @@ public class MediaSourceTestRunner {
}, },
positionUs); positionUs);
prepareCalled.open(); prepareCalled.open();
}
}); });
prepareCalled.block(); prepareCalled.block();
return preparedCountDown; return preparedCountDown;
@ -208,13 +193,7 @@ public class MediaSourceTestRunner {
* @param mediaPeriod The {@link MediaPeriod} to release. * @param mediaPeriod The {@link MediaPeriod} to release.
*/ */
public void releasePeriod(final MediaPeriod mediaPeriod) { public void releasePeriod(final MediaPeriod mediaPeriod) {
runOnPlaybackThread( runOnPlaybackThread(() -> mediaSource.releasePeriod(mediaPeriod));
new Runnable() {
@Override
public void run() {
mediaSource.releasePeriod(mediaPeriod);
}
});
} }
/** /**
@ -222,13 +201,7 @@ public class MediaSourceTestRunner {
* thread. * thread.
*/ */
public void releaseSource() { public void releaseSource() {
runOnPlaybackThread( runOnPlaybackThread(() -> mediaSource.releaseSource(mediaSourceListener));
new Runnable() {
@Override
public void run() {
mediaSource.releaseSource(mediaSourceListener);
}
});
} }
/** /**

View File

@ -81,13 +81,10 @@ public final class TestDownloadManagerListener implements DownloadManager.Listen
downloadFinishedCondition = new CountDownLatch(1); downloadFinishedCondition = new CountDownLatch(1);
} }
dummyMainThread.runOnMainThread( dummyMainThread.runOnMainThread(
new Runnable() { () -> {
@Override
public void run() {
if (downloadManager.isIdle()) { if (downloadManager.isIdle()) {
downloadFinishedCondition.countDown(); downloadFinishedCondition.countDown();
} }
}
}); });
assertThat(downloadFinishedCondition.await(TIMEOUT, TimeUnit.MILLISECONDS)).isTrue(); assertThat(downloadFinishedCondition.await(TIMEOUT, TimeUnit.MILLISECONDS)).isTrue();
if (downloadError != null) { if (downloadError != null) {