android.os.ConditionVariable Java Examples

The following examples show how to use android.os.ConditionVariable. 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 check out the related API usage on the sidebar.
Example #1
Source File: WebViewAppTest.java    From unity-ads-android with 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 #2
Source File: DownloadManager.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #3
Source File: SimpleCache.java    From TelePlus-Android with 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 #4
Source File: SimpleCache.java    From Exoplayer_VLC with 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 #5
Source File: DownloadManager.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: SensorInfoTest.java    From unity-ads-android with 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 #7
Source File: FacebookActivityTestCase.java    From FacebookImageShareIntent with MIT License 6 votes vote down vote up
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 #8
Source File: VideoViewTest.java    From unity-ads-android with 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 #9
Source File: SimpleCache.java    From TelePlus-Android with 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 #10
Source File: WebViewAppTest.java    From unity-ads-android with 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 #11
Source File: WebViewAppTest.java    From unity-ads-android with 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 #12
Source File: WebViewAppTest.java    From unity-ads-android with 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 #13
Source File: WebViewAppTest.java    From unity-ads-android with 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 File: WebViewAppTest.java    From unity-ads-android with 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 #15
Source File: WebViewAppTest.java    From unity-ads-android with 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 #16
Source File: SimpleCache.java    From K-Sonic with 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 #17
Source File: WebViewAppTest.java    From unity-ads-android with 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 #18
Source File: WebViewAppTest.java    From unity-ads-android with 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 #19
Source File: WebViewAppTest.java    From unity-ads-android with 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 #20
Source File: InitializeThread.java    From unity-ads-android with 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 #21
Source File: ClientPropertiesTest.java    From unity-ads-android with 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 #22
Source File: WebViewBridgeInterfaceTest.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeTest () throws TimeoutException {
	WebViewBridgeTestApi.invoked = false;
	WebViewBridgeTestApi.value = null;
	WebViewBridgeTestApi.callback = null;
	WebViewBridgeTestApi.callbackCount = 0;
	nativeCallbackInvoked = false;
	nativeCallbackStatus = null;
	nativeCallbackValue = null;

	final Configuration config = new Configuration(TestUtilities.getTestServerAddress()) {
		@Override
		public Class[] getWebAppApiClassList() {
			return apiTestClassList;
		}
	};

	final ConditionVariable cv = new ConditionVariable();
	Handler handler = new Handler(Looper.getMainLooper());
	handler.postDelayed(new Runnable() {
		@Override
		public void run() {
			WebViewApp.getCurrentApp().setWebAppLoaded(true);
			WebViewApp.getCurrentApp().setWebAppInitialized(true);
			WebViewApp.getCurrentApp().setWebView(new WebView(ClientProperties.getApplicationContext()) {
				@Override
				public void invokeJavascript(String data) {
				}
			});

			cv.open();
		}
	}, 100);

	WebViewApp.create(config);
	boolean success = cv.block(30000);
	if (!success)
		throw new TimeoutException("ConditionVariable was not opened in preparation");
}
 
Example #23
Source File: DefaultAudioSink.java    From MediaSDK with 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 #24
Source File: RequestTest.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidPostWithNullHeadersAndPostBody () throws Exception {
	final ConditionVariable cv = new ConditionVariable();
	MockWebViewApp webViewApp = new MockWebViewApp() {
		@Override
		public boolean sendEvent(Enum eventCategory, Enum eventId, Object... params) {
			EVENT_CATEGORY = eventCategory;
			EVENT_ID = eventId;
			EVENT_PARAMS = params;
			cv.open();

			return true;
		}
	};

	WebViewApp.setCurrentApp(webViewApp);
	Invocation invocation = new Invocation();
	WebViewCallback callback = new WebViewCallback("Test_Valid_Post_No_Headers_Post_Body", invocation.getId());
	Request.post("1", validUrl, "Testing Testing", null, connectTimeout, readTimeout, callback);
	invocation.sendInvocationCallback();

	boolean success = cv.block(30000);

	assertTrue("ConditionVariable was not opened", success);
	assertEquals("Callback status was not OK, successfull callback was expected", CallbackStatus.OK, CALLBACK_STATUS);
	assertNull("Callback error was not NULL, successfull callback was expected", CALLBACK_ERROR);
	assertEquals("Callback params list length was expected to be 2 (callback id and request id in params)", 2, CALLBACK_PARAMS.length);
	assertEquals("Callback first param was expected to be Callback ID", callback.getCallbackId(), CALLBACK_ID);

	assertEquals("Request has changed for some reason", validUrl, EVENT_PARAMS[1]);
	assertEquals("Response code was not OK (200)", 200, EVENT_PARAMS[3]);
	assertEquals("Event ID was incorrect", WebRequestEvent.COMPLETE, EVENT_ID);
	assertEquals("Event Category was incorrect", WebViewEventCategory.REQUEST, EVENT_CATEGORY);
}
 
Example #25
Source File: SimpleCache.java    From Telegram-FOSS with GNU General Public License v2.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 #26
Source File: SettingsTests.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest @MediumTest @LargeTest
public void testSetExecutor() {
    final ConditionVariable condition = new ConditionVariable();

    final Runnable runnable = new Runnable() {
        @Override
        public void run() { }
    };

    final Executor executor = new Executor() {
        @Override
        public void execute(Runnable command) {
            assertEquals(runnable, command);
            command.run();

            condition.open();
        }
    };

    Executor original = Settings.getExecutor();
    try {
        Settings.setExecutor(executor);
        Settings.getExecutor().execute(runnable);

        boolean success = condition.block(5000);
        assertTrue(success);
    } finally {
        Settings.setExecutor(original);
    }
}
 
Example #27
Source File: WebViewAppTest.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveCallback () throws NoSuchMethodException {
	WebViewApp.setCurrentApp(null);
	Method m = getClass().getMethod("nativeCallbackMethod");
	NativeCallback localNativeCallback = new NativeCallback(m);
	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);
	WebViewApp.getCurrentApp().addCallback(localNativeCallback);
	NativeCallback remoteNativeCallback = WebViewApp.getCurrentApp().getCallback(localNativeCallback.getId());
	assertNotNull("The WebApp stored callback should not be NULL", remoteNativeCallback);
	WebViewApp.getCurrentApp().removeCallback(localNativeCallback);
	remoteNativeCallback = WebViewApp.getCurrentApp().getCallback(localNativeCallback.getId());
	assertNull("The WebApp stored callback should be NULL because it was removed", remoteNativeCallback);
}
 
Example #28
Source File: WebViewAppTest.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddCallback () throws NoSuchMethodException {
	WebViewApp.setCurrentApp(null);
	final ConditionVariable cv = new ConditionVariable();

	Method m = getClass().getMethod("nativeCallbackMethod");
	NativeCallback localNativeCallback = new NativeCallback(m);

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

	WebViewApp.getCurrentApp().addCallback(localNativeCallback);
	NativeCallback remoteNativeCallback = WebViewApp.getCurrentApp().getCallback(localNativeCallback.getId());

	assertTrue("ConditionVariable was not opened successfully", success);
	assertNotNull("The WebApp stored callback should not be NULL", remoteNativeCallback);
	assertEquals("The local and the WebApp stored callback should be the same object", localNativeCallback, remoteNativeCallback);
	assertEquals("The local and the WebApp stored callback should have the same ID", localNativeCallback.getId(), remoteNativeCallback.getId());
}
 
Example #29
Source File: InitializeThreadTest.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitializeStateReset() throws InterruptedException {
	final ConditionVariable cv = new ConditionVariable();

	Handler handler = new Handler(Looper.getMainLooper());
	handler.post(new Runnable() {
		@Override
		public void run() {
			webview = new WebView(InstrumentationRegistry.getTargetContext());
			cv.open();
		}
	});
	cv.block(30000);

	WebViewApp.setCurrentApp(new WebViewApp());
	WebViewApp.getCurrentApp().setWebView(webview);
	WebViewApp.getCurrentApp().setWebAppLoaded(true);
	SdkProperties.setInitialized(true);

	Configuration initConfig = new Configuration();
	InitializeThread.InitializeStateReset state = new InitializeThread.InitializeStateReset(initConfig);
	Object nextState = state.execute();

	assertFalse("Init state reset test: SDK is initialized after SDK was reset", SdkProperties.isInitialized());
	assertFalse("Init state reset test: webapp is loaded after SDK was reset", WebViewApp.getCurrentApp().isWebAppLoaded());
	assertTrue("Init state reset test: next state is not config", nextState instanceof InitializeThread.InitializeStateInitModules);

	Configuration config = ((InitializeThread.InitializeStateInitModules)nextState).getConfiguration();

	assertEquals("Init state reset test: next state config url is not set", config.getConfigUrl(), SdkProperties.getConfigUrl());
}
 
Example #30
Source File: RequestTest.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidUrlPostWithNullHeaders () throws Exception {
	final ConditionVariable cv = new ConditionVariable();
	MockWebViewApp webViewApp = new MockWebViewApp() {
		@Override
		public boolean sendEvent(Enum eventCategory, Enum eventId, Object... params) {
			EVENT_CATEGORY = eventCategory;
			EVENT_ID = eventId;
			EVENT_PARAMS = params;
			cv.open();

			return true;
		}
	};

	WebViewApp.setCurrentApp(webViewApp);
	Invocation invocation = new Invocation();
	WebViewCallback callback = new WebViewCallback("Test_InvalidUrl_Post_No_Headers", invocation.getId());
	Request.post("1", invalidUrl, null, null, connectTimeout, readTimeout, callback);
	invocation.sendInvocationCallback();

	boolean success = cv.block(30000);

	assertTrue("ConditionVariable was not opened", success);
	assertEquals("Callback status was not OK, successfull callback was expected", CallbackStatus.OK, CALLBACK_STATUS);
	assertNull("Callback error was not NULL, successfull callback was expected", CALLBACK_ERROR);
	assertEquals("Callback params list length was expected to be 2 (callback id and request id in params)", 2, CALLBACK_PARAMS.length);
	assertEquals("Callback first param was expected to be Callback ID", callback.getCallbackId(), CALLBACK_ID);
	assertEquals("Request has changed for some reason", invalidUrl, EVENT_PARAMS[1]);
	assertEquals("Expected two (3) params in event parameters", 3, EVENT_PARAMS.length);
	assertEquals("Event ID was incorrect", WebRequestEvent.FAILED, EVENT_ID);
	assertEquals("Event Category was incorrect", WebViewEventCategory.REQUEST, EVENT_CATEGORY);
}