Java Code Examples for android.os.ConditionVariable

The following are top voted examples for showing how to use android.os.ConditionVariable. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: airgram   File: AudioTrack.java   View source code 6 votes vote down vote up
/**
 * Creates an audio track using the specified audio capabilities and stream type.
 *
 * @param audioCapabilities The current audio playback capabilities.
 * @param streamType The type of audio stream for the underlying {@link android.media.AudioTrack}.
 */
public AudioTrack(AudioCapabilities audioCapabilities, int streamType) {
  this.audioCapabilities = audioCapabilities;
  this.streamType = streamType;
  releasingConditionVariable = new ConditionVariable(true);
  if (Util.SDK_INT >= 18) {
    try {
      getLatencyMethod =
          android.media.AudioTrack.class.getMethod("getLatency", (Class<?>[]) null);
    } catch (NoSuchMethodException e) {
      // There's no guarantee this method exists. Do nothing.
    }
  }
  if (Util.SDK_INT >= 23) {
    audioTrackUtil = new AudioTrackUtilV23();
  } else if (Util.SDK_INT >= 19) {
    audioTrackUtil = new AudioTrackUtilV19();
  } else {
    audioTrackUtil = new AudioTrackUtil();
  }
  playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT];
  volume = 1.0f;
  startMediaTimeState = START_NOT_SET;
}
 
Example 2
Project: airgram   File: SimpleCache.java   View source code 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<>();
  this.cachedSpans = new HashMap<>();
  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();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 3
Project: chromium-net-for-android   File: CronetUrlRequestContextTest.java   View source code 6 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
public void testInitTwoEnginesSimultaneously() throws Exception {
    final CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit();

    // Threads will block on runBlocker to ensure simultaneous execution.
    ConditionVariable runBlocker = new ConditionVariable(false);
    RequestThread thread1 = new RequestThread(testFramework, mUrl, runBlocker);
    RequestThread thread2 = new RequestThread(testFramework, mUrl404, runBlocker);

    thread1.start();
    thread2.start();
    runBlocker.open();
    thread1.join();
    thread2.join();
    assertEquals(200, thread1.mCallback.mResponseInfo.getHttpStatusCode());
    assertEquals(404, thread2.mCallback.mResponseInfo.getHttpStatusCode());
}
 
Example 4
Project: chromium-net-for-android   File: CronetUrlRequestContextTest.java   View source code 6 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
public void testInitTwoEnginesInSequence() throws Exception {
    final CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit();

    ConditionVariable runBlocker = new ConditionVariable(true);
    RequestThread thread1 = new RequestThread(testFramework, mUrl, runBlocker);
    RequestThread thread2 = new RequestThread(testFramework, mUrl404, runBlocker);

    thread1.start();
    thread1.join();
    thread2.start();
    thread2.join();
    assertEquals(200, thread1.mCallback.mResponseInfo.getHttpStatusCode());
    assertEquals(404, thread2.mCallback.mResponseInfo.getHttpStatusCode());
}
 
Example 5
Project: chromium-net-for-android   File: CronetUrlRequestContextTest.java   View source code 6 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
public void testThreadedStartup() throws Exception {
    final ConditionVariable otherThreadDone = new ConditionVariable();
    final ConditionVariable uiThreadDone = new ConditionVariable();
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
            final CronetEngine.Builder builder =
                    new CronetEngine.Builder(getContext()).setLibraryName("cronet_tests");
            new Thread() {
                public void run() {
                    CronetEngine cronetEngine = builder.build();
                    otherThreadDone.open();
                    cronetEngine.shutdown();
                }
            }.start();
            otherThreadDone.block();
            builder.build().shutdown();
            uiThreadDone.open();
        }
    });
    assertTrue(uiThreadDone.block(1000));
}
 
Example 6
Project: PlusGram   File: AudioTrack.java   View source code 6 votes vote down vote up
/**
 * Creates an audio track using the specified audio capabilities and stream type.
 *
 * @param audioCapabilities The current audio playback capabilities.
 * @param streamType The type of audio stream for the underlying {@link android.media.AudioTrack}.
 */
public AudioTrack(AudioCapabilities audioCapabilities, int streamType) {
  this.audioCapabilities = audioCapabilities;
  this.streamType = streamType;
  releasingConditionVariable = new ConditionVariable(true);
  if (Util.SDK_INT >= 18) {
    try {
      getLatencyMethod =
          android.media.AudioTrack.class.getMethod("getLatency", (Class<?>[]) null);
    } catch (NoSuchMethodException e) {
      // There's no guarantee this method exists. Do nothing.
    }
  }
  if (Util.SDK_INT >= 23) {
    audioTrackUtil = new AudioTrackUtilV23();
  } else if (Util.SDK_INT >= 19) {
    audioTrackUtil = new AudioTrackUtilV19();
  } else {
    audioTrackUtil = new AudioTrackUtil();
  }
  playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT];
  volume = 1.0f;
  startMediaTimeState = START_NOT_SET;
}
 
Example 7
Project: PlusGram   File: SimpleCache.java   View source code 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<>();
  this.cachedSpans = new HashMap<>();
  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();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 8
Project: Exoplayer2Radio   File: SimpleCache.java   View source code 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 9
Project: android_packages_apps_tv   File: ScanFragment.java   View source code 6 votes vote down vote up
public ChannelScanTask(int channelMapId) {
    mActivity = getActivity();
    mChannelMapId = channelMapId;
    if (FAKE_MODE) {
        mScanTsStreamer = new FakeTsStreamer(this);
    } else {
        TunerHal hal = TunerHal.createInstance(mActivity.getApplicationContext());
        if (hal == null) {
            throw new RuntimeException("Failed to open a DVB device");
        }
        mScanTsStreamer = new TunerTsStreamer(hal, this);
    }
    mFileTsStreamer = SCAN_LOCAL_STREAMS ? new FileTsStreamer(this) : null;
    mConditionStopped = new ConditionVariable();
    mChannelDataManager.setChannelScanListener(this, new Handler());
}
 
Example 10
Project: android_packages_apps_tv   File: SimpleSampleBuffer.java   View source code 6 votes vote down vote up
@Override
public void writeSample(int index, SampleHolder sample,
        ConditionVariable conditionVariable) throws IOException {
    sample.data.position(0).limit(sample.size);
    SampleHolder sampleToQueue = mSamplePool.acquireSample(sample.size);
    sampleToQueue.size = sample.size;
    sampleToQueue.clearData();
    sampleToQueue.data.put(sample.data);
    sampleToQueue.timeUs = sample.timeUs;
    sampleToQueue.flags = sample.flags;

    synchronized (this) {
        if (mPlayingSampleQueues[index] != null) {
            mPlayingSampleQueues[index].queueSample(sampleToQueue);
        }
    }
}
 
Example 11
Project: PlatePicks-Android   File: S3WholeBucketIterator.java   View source code 6 votes vote down vote up
/**
 * Constructs this iterator.
 * @param s3Client the S3 client.
 * @param bucketName the S3 bucket name.
 * @param s3ContentPrefix the portion of the s3 object prefix that should be omitted from the relative path
 *                        of the S3ContentSummary objects this iterator returns.
 * @param prefix the s3 object prefix; may be null.
 * @param delimiter the s3 object delimiter; may be null.
 * @param includeDirectories whether to include directories (common prefixes)
 * @param errorHandler an error handler.
 */
public S3WholeBucketIterator(final AmazonS3 s3Client, final String bucketName, final String s3ContentPrefix,
                             final String prefix, final String delimiter, final boolean includeDirectories,
                             final S3ListErrorHandler errorHandler) {
    this.s3Client = s3Client;
    this.bucketName = bucketName;
    this.errorHandler = errorHandler;
    this.s3ContentPrefix = s3ContentPrefix;
    this.prefix = prefix;
    this.delimiter = delimiter;
    this.includeDirectories = includeDirectories;
    summaries = new ConcurrentLinkedQueue<>();
    summaryCount = new AtomicInteger();
    summaryCount.set(0);
    waitingForObjects = new ConditionVariable();
    waitingForReader = new ConditionVariable(true);
    areListingObjects = true;

    // Start the background thread to begin listing objects.
    listingThread = new Thread(this);
    listingThread.start();
}
 
Example 12
Project: miku   File: AudioTrack.java   View source code 6 votes vote down vote up
public AudioTrack() {
  releasingConditionVariable = new ConditionVariable(true);
  if (Util.SDK_INT >= 18) {
    try {
      getLatencyMethod =
          android.media.AudioTrack.class.getMethod("getLatency", (Class<?>[]) null);
    } catch (NoSuchMethodException e) {
      // There's no guarantee this method exists. Do nothing.
    }
  }
  if (Util.SDK_INT >= 19) {
    audioTrackUtil = new AudioTrackUtilV19();
  } else {
    audioTrackUtil = new AudioTrackUtil();
  }
  playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT];
  volume = 1.0f;
  startMediaTimeState = START_NOT_SET;
}
 
Example 13
Project: miku   File: SimpleCache.java   View source code 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<>();
  this.cachedSpans = new HashMap<>();
  this.listeners = new HashMap<>();
  // Start cache initialization.
  final ConditionVariable conditionVariable = new ConditionVariable();
  new Thread() {
    @Override
    public void run() {
      synchronized (SimpleCache.this) {
        conditionVariable.open();
        initialize();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 14
Project: K-Sonic   File: SimpleCache.java   View source code 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 15
Project: ExoPlayer-Demo   File: AudioTrack.java   View source code 6 votes vote down vote up
/**
 * Creates an audio track using the specified audio capabilities and stream type.
 *
 * @param audioCapabilities The current audio playback capabilities.
 * @param streamType The type of audio stream for the underlying {@link android.media.AudioTrack}.
 */
public AudioTrack(AudioCapabilities audioCapabilities, int streamType) {
  this.audioCapabilities = audioCapabilities;
  this.streamType = streamType;
  releasingConditionVariable = new ConditionVariable(true);
  if (Util.SDK_INT >= 18) {
    try {
      getLatencyMethod =
          android.media.AudioTrack.class.getMethod("getLatency", (Class<?>[]) null);
    } catch (NoSuchMethodException e) {
      // There's no guarantee this method exists. Do nothing.
    }
  }
  if (Util.SDK_INT >= 23) {
    audioTrackUtil = new AudioTrackUtilV23();
  } else if (Util.SDK_INT >= 19) {
    audioTrackUtil = new AudioTrackUtilV19();
  } else {
    audioTrackUtil = new AudioTrackUtil();
  }
  playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT];
  volume = 1.0f;
  startMediaTimeState = START_NOT_SET;
}
 
Example 16
Project: ExoPlayer-Demo   File: SimpleCache.java   View source code 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<>();
  this.cachedSpans = new HashMap<>();
  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();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 17
Project: unity-ads-android   File: InitializeThread.java   View source code 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!"));
	}
}
 
Example 18
Project: unity-ads-android   File: ClientPropertiesTest.java   View source code 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 19
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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 21
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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 22
Project: unity-ads-android   File: WebViewAppTest.java   View source code 6 votes vote down vote up
@Test
public void testSendEventShouldSucceed () 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);
	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 23
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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 24
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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 25
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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 26
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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 27
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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 28
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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 29
Project: unity-ads-android   File: WebViewAppTest.java   View source code 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 30
Project: unity-ads-android   File: WebViewAppTest.java   View source code 6 votes vote down vote up
@Test
public void testInvokeCallbackWithErrorShouldSucceed () 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, MockError.TEST_ERROR_1, "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 31
Project: unity-ads-android   File: VideoViewTest.java   View source code 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 32
Project: videoPickPlayer   File: AudioTrack.java   View source code 6 votes vote down vote up
/**
 * @param audioCapabilities The current audio capabilities.
 * @param streamType The type of audio stream for the underlying {@link android.media.AudioTrack}.
 */
public AudioTrack(AudioCapabilities audioCapabilities, int streamType) {
  this.audioCapabilities = audioCapabilities;
  this.streamType = streamType;
  releasingConditionVariable = new ConditionVariable(true);
  if (Util.SDK_INT >= 18) {
    try {
      getLatencyMethod =
          android.media.AudioTrack.class.getMethod("getLatency", (Class<?>[]) null);
    } catch (NoSuchMethodException e) {
      // There's no guarantee this method exists. Do nothing.
    }
  }
  if (Util.SDK_INT >= 23) {
    audioTrackUtil = new AudioTrackUtilV23();
  } else if (Util.SDK_INT >= 19) {
    audioTrackUtil = new AudioTrackUtilV19();
  } else {
    audioTrackUtil = new AudioTrackUtil();
  }
  playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT];
  volume = 1.0f;
  startMediaTimeState = START_NOT_SET;
}
 
Example 33
Project: videoPickPlayer   File: SimpleCache.java   View source code 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<>();
  this.cachedSpans = new HashMap<>();
  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();
      }
    }
  }.start();
  conditionVariable.block();
}
 
Example 34
Project: chromium-net-for-android   File: CronetUrlRequestTest.java   View source code 5 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
@OnlyRunNativeCronet // No destroyed callback for tests
public void testExecutorShutdown() {
    TestUrlRequestCallback callback = new TestUrlRequestCallback();

    callback.setAutoAdvance(false);
    UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getEchoBodyURL(),
            callback, callback.getExecutor(), mTestFramework.mCronetEngine);
    CronetUrlRequest urlRequest = (CronetUrlRequest) builder.build();
    urlRequest.start();
    callback.waitForNextStep();
    assertFalse(callback.isDone());
    assertFalse(urlRequest.isDone());

    final ConditionVariable requestDestroyed = new ConditionVariable(false);
    urlRequest.setOnDestroyedCallbackForTesting(new Runnable() {
        @Override
        public void run() {
            requestDestroyed.open();
        }
    });

    // Shutdown the executor, so posting the task will throw an exception.
    callback.shutdownExecutor();
    ByteBuffer readBuffer = ByteBuffer.allocateDirect(5);
    urlRequest.read(readBuffer);
    // Callback will never be called again because executor is shutdown,
    // but request will be destroyed from network thread.
    requestDestroyed.block();

    assertFalse(callback.isDone());
    assertTrue(urlRequest.isDone());
}
 
Example 35
Project: chromium-net-for-android   File: CronetUrlRequestTest.java   View source code 5 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
@OnlyRunNativeCronet // No adapter to destroy in pure java
// Regression test for crbug.com/564946.
public void testDestroyUploadDataStreamAdapterOnSucceededCallback() throws Exception {
    TestUrlRequestCallback callback = new QuitOnSuccessCallback();
    UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getEchoBodyURL(),
            callback, callback.getExecutor(), mTestFramework.mCronetEngine);

    TestUploadDataProvider dataProvider = new TestUploadDataProvider(
            TestUploadDataProvider.SuccessCallbackMode.SYNC, callback.getExecutor());
    builder.setUploadDataProvider(dataProvider, callback.getExecutor());
    builder.addHeader("Content-Type", "useless/string");
    CronetUrlRequest request = (CronetUrlRequest) builder.build();
    final ConditionVariable uploadDataStreamAdapterDestroyed = new ConditionVariable();
    request.setOnDestroyedUploadCallbackForTesting(new Runnable() {
        @Override
        public void run() {
            uploadDataStreamAdapterDestroyed.open();
        }
    });

    request.start();
    uploadDataStreamAdapterDestroyed.block();

    assertEquals(200, callback.mResponseInfo.getHttpStatusCode());
    assertEquals("", callback.mResponseAsString);
}
 
Example 36
Project: chromium-net-for-android   File: CronetUrlRequestContextTest.java   View source code 5 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
public void testInitAndShutdownOnMainThread() throws Exception {
    final CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit();
    final ConditionVariable block = new ConditionVariable(false);

    // Post a task to main thread to init and shutdown on the main thread.
    Runnable blockingTask = new Runnable() {
        @Override
        public void run() {
            // Create new request context, loading the library.
            final CronetEngine cronetEngine = testFramework.initCronetEngine();
            // Shutdown right after init.
            cronetEngine.shutdown();
            // Verify that context is shutdown.
            try {
                cronetEngine.stopNetLog();
                fail("Should throw an exception.");
            } catch (Exception e) {
                assertEquals("Engine is shut down.", e.getMessage());
            }
            block.open();
        }
    };
    new Handler(Looper.getMainLooper()).post(blockingTask);
    // Wait for shutdown to complete on main thread.
    block.block();
}
 
Example 37
Project: chromium-net-for-android   File: TestBidirectionalStreamCallback.java   View source code 5 votes vote down vote up
/**
 * Returns {@code false} if the callback should continue to advance the
 * stream.
 */
private boolean maybeThrowCancelOrPause(
        final BidirectionalStream stream, ConditionVariable stepBlock) {
    if (mResponseStep != mFailureStep || mFailureType == FailureType.NONE) {
        if (!mAutoAdvance) {
            stepBlock.open();
            return true;
        }
        return false;
    }

    if (mFailureType == FailureType.THROW_SYNC) {
        throw new IllegalStateException("Callback Exception.");
    }
    Runnable task = new Runnable() {
        public void run() {
            stream.cancel();
        }
    };
    if (mFailureType == FailureType.CANCEL_ASYNC
            || mFailureType == FailureType.CANCEL_ASYNC_WITHOUT_PAUSE) {
        getExecutor().execute(task);
    } else {
        task.run();
    }
    return mFailureType != FailureType.CANCEL_ASYNC_WITHOUT_PAUSE;
}
 
Example 38
Project: chromium-net-for-android   File: BidirectionalStreamTest.java   View source code 5 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
@OnlyRunNativeCronet
public void testExecutorShutdownBeforeStreamIsDone() {
    // Test that stream is destroyed even if executor is shut down and rejects posting tasks.
    TestBidirectionalStreamCallback callback = new TestBidirectionalStreamCallback();
    callback.setAutoAdvance(false);
    BidirectionalStream.Builder builder =
            new BidirectionalStream.Builder(Http2TestServer.getEchoMethodUrl(), callback,
                    callback.getExecutor(), mTestFramework.mCronetEngine);
    CronetBidirectionalStream stream =
            (CronetBidirectionalStream) builder.setHttpMethod("GET").build();
    stream.start();
    callback.waitForNextReadStep();
    assertFalse(callback.isDone());
    assertFalse(stream.isDone());

    final ConditionVariable streamDestroyed = new ConditionVariable(false);
    stream.setOnDestroyedCallbackForTesting(new Runnable() {
        @Override
        public void run() {
            streamDestroyed.open();
        }
    });

    // Shut down the executor, so posting the task will throw an exception.
    callback.shutdownExecutor();
    ByteBuffer readBuffer = ByteBuffer.allocateDirect(5);
    stream.read(readBuffer);
    // Callback will never be called again because executor is shut down,
    // but stream will be destroyed from network thread.
    streamDestroyed.block();

    assertFalse(callback.isDone());
    assertTrue(stream.isDone());
}
 
Example 39
Project: medialibrary   File: GalleryUtils.java   View source code 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);
}
 
Example 40
Project: VirtualHook   File: VClientImpl.java   View source code 5 votes vote down vote up
public void bindApplication(final String packageName, final String processName) {
    if (Looper.getMainLooper() == Looper.myLooper()) {
        bindApplicationNoCheck(packageName, processName, new ConditionVariable());
    } else {
        final ConditionVariable lock = new ConditionVariable();
        VirtualRuntime.getUIHandler().post(new Runnable() {
            @Override
            public void run() {
                bindApplicationNoCheck(packageName, processName, lock);
                lock.open();
            }
        });
        lock.block();
    }
}