Java Code Examples for android.os.ConditionVariable

The following examples show how to use android.os.ConditionVariable. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Stops all of the tasks and releases resources. If the action file isn't up to date, waits for
 * the changes to be written. The manager must not be accessed after this method has been called.
 */
public void release() {
  if (released) {
    return;
  }
  released = true;
  for (int i = 0; i < tasks.size(); i++) {
    tasks.get(i).stop();
  }
  final ConditionVariable fileIOFinishedCondition = new ConditionVariable();
  fileIOHandler.post(new Runnable() {
    @Override
    public void run() {
      fileIOFinishedCondition.open();
    }
  });
  fileIOFinishedCondition.block();
  fileIOThread.quit();
  logd("Released");
}
 
Example 2
Source Project: TelePlus-Android   Source File: SimpleCache.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs the cache. The cache will delete any unrecognized files from the directory. Hence
 * the directory cannot be used to store other files.
 *
 * @param cacheDir A dedicated cache directory.
 * @param evictor The evictor to be used.
 * @param index The CachedContentIndex to be used.
 */
/*package*/ SimpleCache(File cacheDir, CacheEvictor evictor, CachedContentIndex index) {
  if (!lockFolder(cacheDir)) {
    throw new IllegalStateException("Another SimpleCache instance uses the folder: " + cacheDir);
  }

  this.cacheDir = cacheDir;
  this.evictor = evictor;
  this.index = index;
  this.listeners = new HashMap<>();

  // Start cache initialization.
  final ConditionVariable conditionVariable = new ConditionVariable();
  new Thread("SimpleCache.initialize()") {
    @Override
    public void run() {
      synchronized (SimpleCache.this) {
        conditionVariable.open();
        initialize();
        SimpleCache.this.evictor.onCacheInitialized();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 3
/**
 * Stops all of the tasks and releases resources. If the action file isn't up to date, waits for
 * the changes to be written. The manager must not be accessed after this method has been called.
 */
public void release() {
  if (released) {
    return;
  }
  released = true;
  for (int i = 0; i < tasks.size(); i++) {
    tasks.get(i).stop();
  }
  final ConditionVariable fileIOFinishedCondition = new ConditionVariable();
  fileIOHandler.post(new Runnable() {
    @Override
    public void run() {
      fileIOFinishedCondition.open();
    }
  });
  fileIOFinishedCondition.block();
  fileIOThread.quit();
  logd("Released");
}
 
Example 4
Source Project: TelePlus-Android   Source File: SimpleCache.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs the cache. The cache will delete any unrecognized files from the directory. Hence
 * the directory cannot be used to store other files.
 *
 * @param cacheDir A dedicated cache directory.
 * @param evictor The evictor to be used.
 * @param index The CachedContentIndex to be used.
 */
/*package*/ SimpleCache(File cacheDir, CacheEvictor evictor, CachedContentIndex index) {
  if (!lockFolder(cacheDir)) {
    throw new IllegalStateException("Another SimpleCache instance uses the folder: " + cacheDir);
  }

  this.cacheDir = cacheDir;
  this.evictor = evictor;
  this.index = index;
  this.listeners = new HashMap<>();

  // Start cache initialization.
  final ConditionVariable conditionVariable = new ConditionVariable();
  new Thread("SimpleCache.initialize()") {
    @Override
    public void run() {
      synchronized (SimpleCache.this) {
        conditionVariable.open();
        initialize();
        SimpleCache.this.evictor.onCacheInitialized();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 5
Source Project: K-Sonic   Source File: SimpleCache.java    License: MIT License 6 votes vote down vote up
/**
 * Constructs the cache. The cache will delete any unrecognized files from the directory. Hence
 * the directory cannot be used to store other files.
 *
 * @param cacheDir A dedicated cache directory.
 * @param evictor The evictor to be used.
 * @param secretKey If not null, cache keys will be stored encrypted on filesystem using AES/CBC.
 *     The key must be 16 bytes long.
 */
public SimpleCache(File cacheDir, CacheEvictor evictor, byte[] secretKey) {
  this.cacheDir = cacheDir;
  this.evictor = evictor;
  this.lockedSpans = new HashMap<>();
  this.index = new CachedContentIndex(cacheDir, secretKey);
  this.listeners = new HashMap<>();
  // Start cache initialization.
  final ConditionVariable conditionVariable = new ConditionVariable();
  new Thread("SimpleCache.initialize()") {
    @Override
    public void run() {
      synchronized (SimpleCache.this) {
        conditionVariable.open();
        try {
          initialize();
        } catch (CacheException e) {
          initializationException = e;
        }
        SimpleCache.this.evictor.onCacheInitialized();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 6
Source Project: unity-ads-android   Source File: InitializeThread.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public InitializeState execute() {
	DeviceLog.error("Unity Ads init: network error, waiting for connection events");

	_conditionVariable = new ConditionVariable();
	ConnectivityMonitor.addListener(this);

	if (_conditionVariable.block(10000L * 60L)) {
		ConnectivityMonitor.removeListener(this);
		return _erroredState;
	}
	else {
		ConnectivityMonitor.removeListener(this);
		return new InitializeStateError("network error", new Exception("No connected events within the timeout!"), _configuration);
	}
}
 
Example 7
Source Project: unity-ads-android   Source File: ClientPropertiesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSetActivity () throws InterruptedException {
	final ConditionVariable cv = new ConditionVariable();

	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			MockActivity act = new MockActivity();
			ClientProperties.setActivity(act);
			cv.open();
		}
	});

	boolean success = cv.block(10000);
	assertTrue("ConditionVariable was not opened!", success);
	assertNotNull("Activity should not be null after setting it", ClientProperties.getActivity());
}
 
Example 8
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSetConfiguration () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();

	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppLoaded(true);
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean success = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", success);

	final Configuration conf = new Configuration(TestUtilities.getTestServerAddress());
	WebViewApp.getCurrentApp().setConfiguration(conf);

	assertNotNull("Current WebApp configuration should not be null", WebViewApp.getCurrentApp().getConfiguration());
	assertEquals("Local configuration and current WebApp configuration should be the same object", conf, WebViewApp.getCurrentApp().getConfiguration());
}
 
Example 9
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSetWebAppLoaded () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();

	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean success = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", success);
	assertFalse("WebApp should not be loaded. It was just created", WebViewApp.getCurrentApp().isWebAppLoaded());
	WebViewApp.getCurrentApp().setWebAppLoaded(true);
	assertTrue("WebApp should now be \"loaded\". We set the status to true", WebViewApp.getCurrentApp().isWebAppLoaded());
}
 
Example 10
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSendEventShouldFail () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();

	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean cvsuccess = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", cvsuccess);
	boolean success = WebViewApp.getCurrentApp().sendEvent(MockEventCategory.TEST_CATEGORY_1, MockEvent.TEST_EVENT_1);
	assertFalse("sendEvent -method should've returned false", success);
	assertFalse("WebView invokeJavascript should've not been invoked but was (webviewapp is not loaded so no call should have occured)", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
	assertNull("The invoked JavaScript string should be null (webviewapp is not loaded so no call should have occured)", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
 
Example 11
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSendEventWithParamsShouldSucceed () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();
	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppLoaded(true);
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean cvsuccess = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", cvsuccess);
	boolean success = WebViewApp.getCurrentApp().sendEvent(MockEventCategory.TEST_CATEGORY_1, MockEvent.TEST_EVENT_1, "Test", 12345, true);
	assertTrue("sendEvent should have succeeded", success);
	assertTrue("WebView invokeJavascript should've been invoked but was not", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
	assertNotNull("The invoked JavaScript string should not be null", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
 
Example 12
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeMethodShouldFailWebAppNotLoaded () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();
	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppLoaded(false);
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean cvsuccess = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", cvsuccess);
	Method m = getClass().getMethod("testNativeCallbackMethod");
	boolean success = WebViewApp.getCurrentApp().invokeMethod("TestClass", "testMethod", m);
	assertFalse("invokeMethod -method should've returned false", success);
	assertFalse("WebView invokeJavascript should've not been invoked but was (webviewapp is not loaded so no call should have occured)", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
	assertNull("The invoked JavaScript string should be null (webviewapp is not loaded so no call should have occured)", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
 
Example 13
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeMethodShouldSucceedMethodNull () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();
	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppLoaded(true);
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean cvsuccess = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", cvsuccess);
	Method m = null;
	boolean success = WebViewApp.getCurrentApp().invokeMethod("TestClass", "testMethod", m);
	assertTrue("invokeMethod -method should've returned true", success);
	assertTrue("WebView invokeJavascript should've succeeded but didn't", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
	assertNotNull("The invoked JavaScript string should not be null.", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
 
Example 14
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeMethodShouldSucceed () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();
	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppLoaded(true);
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean cvsuccess = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", cvsuccess);
	Method m = getClass().getMethod("testNativeCallbackMethod");
	boolean success = WebViewApp.getCurrentApp().invokeMethod("TestClass", "testMethod", m);
	assertTrue("invokeMethod -method should've returned true", success);
	assertTrue("WebView invokeJavascript should've succeeded but didn't", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
	assertNotNull("The invoked JavaScript string should not be null.", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
 
Example 15
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeMethodWithParamsShouldSucceed () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();
	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppLoaded(true);
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean cvsuccess = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", cvsuccess);
	Method m = getClass().getMethod("testNativeCallbackMethod");
	boolean success = WebViewApp.getCurrentApp().invokeMethod("TestClass", "testMethod", m, "Test", 12345, true);
	assertTrue("invokeMethod -method should've returned true", success);
	assertTrue("WebView invokeJavascript should've succeeded but didn't", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
	assertNotNull("The invoked JavaScript string should not be null.", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
 
Example 16
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeCallbackShouldFailWebAppNotLoaded () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();
	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean cvsuccess = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", cvsuccess);
	Invocation invocation = new Invocation();
	invocation.setInvocationResponse(CallbackStatus.OK, null, "Test", 12345, true);
	boolean success = WebViewApp.getCurrentApp().invokeCallback(invocation);
	assertFalse("invokeCallback -method should've returned false (webapp not loaded)", success);
	assertFalse("WebView invokeJavascript should've not been invoked but was (webviewapp is not loaded so no call should have occured)", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
	assertNull("The invoked JavaScript string should be null (webviewapp is not loaded so no call should have occured)", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
 
Example 17
Source Project: unity-ads-android   Source File: WebViewAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeCallbackShouldSucceed () throws Exception {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();
	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			WebViewApp.setCurrentApp(new WebViewApp());
			WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
			WebViewApp.getCurrentApp().setWebAppLoaded(true);
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			cv.open();
		}
	});

	boolean cvsuccess = cv.block(10000);
	assertTrue("ConditionVariable was not opened successfully", cvsuccess);
	Invocation invocation = new Invocation();
	invocation.setInvocationResponse(CallbackStatus.OK, null, "Test", 12345, true);
	boolean success = WebViewApp.getCurrentApp().invokeCallback(invocation);
	assertTrue("invokeCallback -method should've returned true", success);
	assertTrue("WebView invokeJavascript should've been invoked but was not", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
	assertNotNull("The invoked JavaScript string should not be null", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
 
Example 18
Source Project: unity-ads-android   Source File: VideoViewTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@RequiresDevice
public void testConstruct () throws Exception {
	final ConditionVariable cv = new ConditionVariable();
	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			VideoPlayerView vp = new VideoPlayerView(getInstrumentation().getTargetContext());
			assertNotNull("VideoPlayerView should not be null after constructing", vp);
			cv.open();
		}
	});

	boolean success = cv.block(30000);
	assertTrue("Condition variable was not opened properly: VideoPlayer was not created", success);
}
 
Example 19
Source Project: Exoplayer_VLC   Source File: SimpleCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructs the cache. The cache will delete any unrecognized files from the directory. Hence
 * the directory cannot be used to store other files.
 *
 * @param cacheDir A dedicated cache directory.
 */
public SimpleCache(File cacheDir, CacheEvictor evictor) {
  this.cacheDir = cacheDir;
  this.evictor = evictor;
  this.lockedSpans = new HashMap<String, CacheSpan>();
  this.cachedSpans = new HashMap<String, TreeSet<CacheSpan>>();
  this.listeners = new HashMap<String, ArrayList<Listener>>();
  // Start cache initialization.
  final ConditionVariable conditionVariable = new ConditionVariable();
  new Thread() {
    @Override
    public void run() {
      synchronized (SimpleCache.this) {
        conditionVariable.open();
        initialize();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 20
Source Project: unity-ads-android   Source File: SensorInfoTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAccelerometerData() throws Exception {
	SensorInfoListener.startAccelerometerListener(SensorManager.SENSOR_DELAY_NORMAL);

	ConditionVariable cv = new ConditionVariable();
	cv.block(300);

	JSONObject accelerometerData = SensorInfoListener.getAccelerometerData();

	assertNotNull("Accelerometer shouldn't be null", accelerometerData);

	double x = accelerometerData.getDouble("x");
	double y = accelerometerData.getDouble("y");
	double z = accelerometerData.getDouble("z");

	assertTrue(x != 0);
	assertTrue(y != 0);
	assertTrue(z != 0);
}
 
Example 21
protected void runOnBlockerThread(final Runnable runnable, boolean waitForCompletion) {
    Runnable runnableToPost = runnable;
    final ConditionVariable condition = waitForCompletion ? new ConditionVariable(!waitForCompletion) : null;

    if (waitForCompletion) {
        runnableToPost = new Runnable() {
            @Override
            public void run() {
                runnable.run();
                condition.open();
            }
        };
    }

    TestBlocker blocker = getTestBlocker();
    Handler handler = blocker.getHandler();
    handler.post(runnableToPost);

    if (waitForCompletion) {
        boolean success = condition.block(10000);
        assertTrue(success);
    }
}
 
Example 22
Source Project: MediaSDK   Source File: DefaultAudioSink.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new default audio sink, optionally using float output for high resolution PCM and
 * with the specified {@code audioProcessorChain}.
 *
 * @param audioCapabilities The audio capabilities for playback on this device. May be null if the
 *     default capabilities (no encoded audio passthrough support) should be assumed.
 * @param audioProcessorChain An {@link AudioProcessorChain} which is used to apply playback
 *     parameters adjustments. The instance passed in must not be reused in other sinks.
 * @param enableConvertHighResIntPcmToFloat Whether to enable conversion of high resolution
 *     integer PCM to 32-bit float for output, if possible. Functionality that uses 16-bit integer
 *     audio processing (for example, speed and pitch adjustment) will not be available when float
 *     output is in use.
 */
public DefaultAudioSink(
    @Nullable AudioCapabilities audioCapabilities,
    AudioProcessorChain audioProcessorChain,
    boolean enableConvertHighResIntPcmToFloat) {
  this.audioCapabilities = audioCapabilities;
  this.audioProcessorChain = Assertions.checkNotNull(audioProcessorChain);
  this.enableConvertHighResIntPcmToFloat = enableConvertHighResIntPcmToFloat;
  releasingConditionVariable = new ConditionVariable(true);
  audioTrackPositionTracker = new AudioTrackPositionTracker(new PositionTrackerListener());
  channelMappingAudioProcessor = new ChannelMappingAudioProcessor();
  trimmingAudioProcessor = new TrimmingAudioProcessor();
  ArrayList<AudioProcessor> toIntPcmAudioProcessors = new ArrayList<>();
  Collections.addAll(
      toIntPcmAudioProcessors,
      new ResamplingAudioProcessor(),
      channelMappingAudioProcessor,
      trimmingAudioProcessor);
  Collections.addAll(toIntPcmAudioProcessors, audioProcessorChain.getAudioProcessors());
  toIntPcmAvailableAudioProcessors = toIntPcmAudioProcessors.toArray(new AudioProcessor[0]);
  toFloatPcmAvailableAudioProcessors = new AudioProcessor[] {new FloatResamplingAudioProcessor()};
  volume = 1.0f;
  startMediaTimeState = START_NOT_SET;
  audioAttributes = AudioAttributes.DEFAULT;
  audioSessionId = C.AUDIO_SESSION_ID_UNSET;
  auxEffectInfo = new AuxEffectInfo(AuxEffectInfo.NO_AUX_EFFECT_ID, 0f);
  playbackParameters = PlaybackParameters.DEFAULT;
  drainingAudioProcessorIndex = C.INDEX_UNSET;
  activeAudioProcessors = new AudioProcessor[0];
  outputBuffers = new ByteBuffer[0];
  playbackParametersCheckpoints = new ArrayDeque<>();
}
 
Example 23
Source Project: MediaSDK   Source File: SimpleCache.java    License: Apache License 2.0 5 votes vote down vote up
SimpleCache(
    File cacheDir,
    CacheEvictor evictor,
    CachedContentIndex contentIndex,
    @Nullable CacheFileMetadataIndex fileIndex) {
  if (!lockFolder(cacheDir)) {
    throw new IllegalStateException("Another SimpleCache instance uses the folder: " + cacheDir);
  }

  this.cacheDir = cacheDir;
  this.evictor = evictor;
  this.contentIndex = contentIndex;
  this.fileIndex = fileIndex;
  listeners = new HashMap<>();
  random = new Random();
  touchCacheSpans = evictor.requiresCacheSpanTouches();
  uid = UID_UNSET;

  // Start cache initialization.
  final ConditionVariable conditionVariable = new ConditionVariable();
  new Thread("SimpleCache.initialize()") {
    @Override
    public void run() {
      synchronized (SimpleCache.this) {
        conditionVariable.open();
        initialize();
        SimpleCache.this.evictor.onCacheInitialized();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 24
Source Project: android_9.0.0_r45   Source File: AudioPlaybackQueueItem.java    License: Apache License 2.0 5 votes vote down vote up
AudioPlaybackQueueItem(UtteranceProgressDispatcher dispatcher,
        Object callerIdentity,
        Context context, Uri uri, AudioOutputParams audioParams) {
    super(dispatcher, callerIdentity);

    mContext = context;
    mUri = uri;
    mAudioParams = audioParams;

    mDone = new ConditionVariable();
    mPlayer = null;
    mFinished = false;
}
 
Example 25
Source Project: android_9.0.0_r45   Source File: GLThreadManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Configure the GL renderer for the given set of output surfaces, and block until
 * this configuration has been applied.
 *
 * @param surfaces a collection of pairs of {@link android.view.Surface}s and their
 *                 corresponding sizes to configure.
 * @param collector a {@link CaptureCollector} to retrieve requests from.
 */
public void setConfigurationAndWait(Collection<Pair<Surface, Size>> surfaces,
                                    CaptureCollector collector) {
    checkNotNull(collector, "collector must not be null");
    Handler handler = mGLHandlerThread.getHandler();

    final ConditionVariable condition = new ConditionVariable(/*closed*/false);
    ConfigureHolder configure = new ConfigureHolder(condition, surfaces, collector);

    Message m = handler.obtainMessage(MSG_NEW_CONFIGURATION, /*arg1*/0, /*arg2*/0, configure);
    handler.sendMessage(m);

    // Block until configuration applied.
    condition.block();
}
 
Example 26
/**
 * Constructs an instance. Call {@link #release()} when the instance is no longer required.
 *
 * @param uuid The UUID of the drm scheme.
 * @param mediaDrm An underlying {@link ExoMediaDrm} for use by the manager.
 * @param callback Performs key and provisioning requests.
 * @param optionalKeyRequestParameters An optional map of parameters to pass as the last argument
 *     to {@link MediaDrm#getKeyRequest(byte[], byte[], String, int, HashMap)}. May be null.
 * @see DefaultDrmSessionManager#DefaultDrmSessionManager(java.util.UUID, ExoMediaDrm,
 *     MediaDrmCallback, HashMap, Handler, DefaultDrmSessionEventListener)
 */
public OfflineLicenseHelper(
    UUID uuid,
    ExoMediaDrm<T> mediaDrm,
    MediaDrmCallback callback,
    HashMap<String, String> optionalKeyRequestParameters) {
  handlerThread = new HandlerThread("OfflineLicenseHelper");
  handlerThread.start();
  conditionVariable = new ConditionVariable();
  DefaultDrmSessionEventListener eventListener =
      new DefaultDrmSessionEventListener() {
        @Override
        public void onDrmKeysLoaded() {
          conditionVariable.open();
        }

        @Override
        public void onDrmSessionManagerError(Exception e) {
          conditionVariable.open();
        }

        @Override
        public void onDrmKeysRestored() {
          conditionVariable.open();
        }

        @Override
        public void onDrmKeysRemoved() {
          conditionVariable.open();
        }
      };
  drmSessionManager =
      new DefaultDrmSessionManager<>(uuid, mediaDrm, callback, optionalKeyRequestParameters);
  drmSessionManager.addListener(new Handler(handlerThread.getLooper()), eventListener);
}
 
Example 27
/**
 * Creates a new default audio sink, optionally using float output for high resolution PCM and
 * with the specified {@code audioProcessorChain}.
 *
 * @param audioCapabilities The audio capabilities for playback on this device. May be null if the
 *     default capabilities (no encoded audio passthrough support) should be assumed.
 * @param audioProcessorChain An {@link AudioProcessorChain} which is used to apply playback
 *     parameters adjustments. The instance passed in must not be reused in other sinks.
 * @param enableConvertHighResIntPcmToFloat Whether to enable conversion of high resolution
 *     integer PCM to 32-bit float for output, if possible. Functionality that uses 16-bit integer
 *     audio processing (for example, speed and pitch adjustment) will not be available when float
 *     output is in use.
 */
public DefaultAudioSink(
    @Nullable AudioCapabilities audioCapabilities,
    AudioProcessorChain audioProcessorChain,
    boolean enableConvertHighResIntPcmToFloat) {
  this.audioCapabilities = audioCapabilities;
  this.audioProcessorChain = Assertions.checkNotNull(audioProcessorChain);
  this.enableConvertHighResIntPcmToFloat = enableConvertHighResIntPcmToFloat;
  releasingConditionVariable = new ConditionVariable(true);
  audioTrackPositionTracker = new AudioTrackPositionTracker(new PositionTrackerListener());
  channelMappingAudioProcessor = new ChannelMappingAudioProcessor();
  trimmingAudioProcessor = new TrimmingAudioProcessor();
  ArrayList<AudioProcessor> toIntPcmAudioProcessors = new ArrayList<>();
  Collections.addAll(
      toIntPcmAudioProcessors,
      new ResamplingAudioProcessor(),
      channelMappingAudioProcessor,
      trimmingAudioProcessor);
  Collections.addAll(toIntPcmAudioProcessors, audioProcessorChain.getAudioProcessors());
  toIntPcmAvailableAudioProcessors =
      toIntPcmAudioProcessors.toArray(new AudioProcessor[toIntPcmAudioProcessors.size()]);
  toFloatPcmAvailableAudioProcessors = new AudioProcessor[] {new FloatResamplingAudioProcessor()};
  volume = 1.0f;
  startMediaTimeState = START_NOT_SET;
  audioAttributes = AudioAttributes.DEFAULT;
  audioSessionId = C.AUDIO_SESSION_ID_UNSET;
  playbackParameters = PlaybackParameters.DEFAULT;
  drainingAudioProcessorIndex = C.INDEX_UNSET;
  activeAudioProcessors = new AudioProcessor[0];
  outputBuffers = new ByteBuffer[0];
  playbackParametersCheckpoints = new ArrayDeque<>();
}
 
Example 28
/**
 * Constructs an instance. Call {@link #release()} when the instance is no longer required.
 *
 * @param uuid The UUID of the drm scheme.
 * @param mediaDrm An underlying {@link ExoMediaDrm} for use by the manager.
 * @param callback Performs key and provisioning requests.
 * @param optionalKeyRequestParameters An optional map of parameters to pass as the last argument
 *     to {@link MediaDrm#getKeyRequest(byte[], byte[], String, int, HashMap)}. May be null.
 * @see DefaultDrmSessionManager#DefaultDrmSessionManager(java.util.UUID, ExoMediaDrm,
 *     MediaDrmCallback, HashMap, Handler, DefaultDrmSessionEventListener)
 */
public OfflineLicenseHelper(
    UUID uuid,
    ExoMediaDrm<T> mediaDrm,
    MediaDrmCallback callback,
    HashMap<String, String> optionalKeyRequestParameters) {
  handlerThread = new HandlerThread("OfflineLicenseHelper");
  handlerThread.start();
  conditionVariable = new ConditionVariable();
  DefaultDrmSessionEventListener eventListener =
      new DefaultDrmSessionEventListener() {
        @Override
        public void onDrmKeysLoaded() {
          conditionVariable.open();
        }

        @Override
        public void onDrmSessionManagerError(Exception e) {
          conditionVariable.open();
        }

        @Override
        public void onDrmKeysRestored() {
          conditionVariable.open();
        }

        @Override
        public void onDrmKeysRemoved() {
          conditionVariable.open();
        }
      };
  drmSessionManager =
      new DefaultDrmSessionManager<>(uuid, mediaDrm, callback, optionalKeyRequestParameters);
  drmSessionManager.addListener(new Handler(handlerThread.getLooper()), eventListener);
}
 
Example 29
/**
 * Creates a new default audio sink, optionally using float output for high resolution PCM and
 * with the specified {@code audioProcessorChain}.
 *
 * @param audioCapabilities The audio capabilities for playback on this device. May be null if the
 *     default capabilities (no encoded audio passthrough support) should be assumed.
 * @param audioProcessorChain An {@link AudioProcessorChain} which is used to apply playback
 *     parameters adjustments. The instance passed in must not be reused in other sinks.
 * @param enableConvertHighResIntPcmToFloat Whether to enable conversion of high resolution
 *     integer PCM to 32-bit float for output, if possible. Functionality that uses 16-bit integer
 *     audio processing (for example, speed and pitch adjustment) will not be available when float
 *     output is in use.
 */
public DefaultAudioSink(
    @Nullable AudioCapabilities audioCapabilities,
    AudioProcessorChain audioProcessorChain,
    boolean enableConvertHighResIntPcmToFloat) {
  this.audioCapabilities = audioCapabilities;
  this.audioProcessorChain = Assertions.checkNotNull(audioProcessorChain);
  this.enableConvertHighResIntPcmToFloat = enableConvertHighResIntPcmToFloat;
  releasingConditionVariable = new ConditionVariable(true);
  audioTrackPositionTracker = new AudioTrackPositionTracker(new PositionTrackerListener());
  channelMappingAudioProcessor = new ChannelMappingAudioProcessor();
  trimmingAudioProcessor = new TrimmingAudioProcessor();
  ArrayList<AudioProcessor> toIntPcmAudioProcessors = new ArrayList<>();
  Collections.addAll(
      toIntPcmAudioProcessors,
      new ResamplingAudioProcessor(),
      channelMappingAudioProcessor,
      trimmingAudioProcessor);
  Collections.addAll(toIntPcmAudioProcessors, audioProcessorChain.getAudioProcessors());
  toIntPcmAvailableAudioProcessors =
      toIntPcmAudioProcessors.toArray(new AudioProcessor[toIntPcmAudioProcessors.size()]);
  toFloatPcmAvailableAudioProcessors = new AudioProcessor[] {new FloatResamplingAudioProcessor()};
  volume = 1.0f;
  startMediaTimeState = START_NOT_SET;
  audioAttributes = AudioAttributes.DEFAULT;
  audioSessionId = C.AUDIO_SESSION_ID_UNSET;
  playbackParameters = PlaybackParameters.DEFAULT;
  drainingAudioProcessorIndex = C.INDEX_UNSET;
  activeAudioProcessors = new AudioProcessor[0];
  outputBuffers = new ByteBuffer[0];
  playbackParametersCheckpoints = new ArrayDeque<>();
}
 
Example 30
Source Project: medialibrary   Source File: GalleryUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void fakeBusy(ThreadPool.JobContext jc, int timeout) {
    final ConditionVariable cv = new ConditionVariable();
    jc.setCancelListener(new ThreadPool.CancelListener() {
        @Override
        public void onCancel() {
            cv.open();
        }
    });
    cv.block(timeout);
    jc.setCancelListener(null);
}