@SmallTest
  @Feature({"Cronet"})
  public void testInitAndShutdownOnMainThread() throws Exception {
    final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
    final ConditionVariable block = new ConditionVariable(false);

    // Post a task to main thread to init and shutdown on the main thread.
    Runnable blockingTask =
        new Runnable() {
          public void run() {
            // Create new request context, loading the library.
            final CronetEngine cronetEngine = activity.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();
  }
 /** Waits until the camera preview is up running */
 public boolean waitForPreviewDone(long timeOutMs) {
   if (!mPreviewDone.block(timeOutMs)) {
     // timeout could be expected or unexpected. The caller will decide.
     Log.w(TAG, "waitForPreviewDone timed out after " + timeOutMs + "ms");
     return false;
   }
   mPreviewDone.close();
   return true;
 }
 // For debugging, it will block the caller for timeout millis.
 public static void fakeBusy(JobContext jc, int timeout) {
   final ConditionVariable cv = new ConditionVariable();
   jc.setCancelListener(
       new CancelListener() {
         public void onCancel() {
           cv.open();
         }
       });
   cv.block(timeout);
   jc.setCancelListener(null);
 }
 public void run() {
   for (int i = 0; i < 4; ++i) {
     showNotification(
         R.drawable.stat_happy, R.string.status_bar_notifications_happy_message);
     if (mCondition.block(5 * 1000)) break;
     showNotification(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message);
     if (mCondition.block(5 * 1000)) break;
     showNotification(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message);
     if (mCondition.block(5 * 1000)) break;
   }
   // Done with our work...  stop the service!
   NotifyingService.this.stopSelf();
 }
 @Override
 public void onDestroy() {
   Log.i(TAG, "onDestroy");
   run_flg = false;
   this.stopSelf();
   mCondition.open();
 }
 private void stopAlert(Alarm alarm) {
   mVibrator.cancel();
   mCondition.open();
   mNotificationManager.cancel(alarm.hashCode());
   Log.d(TAG, "Stoped the alert.: " + alarm.dump());
   stopSelf();
 }
 @Override
 public void onDestroy() {
   // Cancel the persistent notification.
   mNM.cancel(MOOD_NOTIFICATIONS);
   // Stop the thread from generating further notifications
   mCondition.open();
 }
 public String getResult() {
   eventHandled.block(30000);
   if (result.message == null) {
     throw new RuntimeException("Timed out waiting for result for JavaScript");
   }
   return result.message;
 }
 @Override
 public void onSurfaceTextureUpdated(SurfaceTexture surface) {
   // Invoked every time there's a new Camera preview frame
   if (!mFirstPreviewAvailable) {
     mFirstPreviewAvailable = true;
     mPreviewDone.open();
   }
 }
  @Override
  public void process(FilterContext context) {
    if (mLogVerbose) Log.v(TAG, "Processing new frame");

    // First, get new frame if available
    if (mWaitForNewFrame || mFirstFrame) {
      boolean gotNewFrame;
      if (mWaitTimeout != 0) {
        gotNewFrame = mNewFrameAvailable.block(mWaitTimeout);
        if (!gotNewFrame) {
          if (!mCloseOnTimeout) {
            throw new RuntimeException("Timeout waiting for new frame");
          } else {
            if (mLogVerbose) Log.v(TAG, "Timeout waiting for a new frame. Closing.");
            closeOutputPort("video");
            return;
          }
        }
      } else {
        mNewFrameAvailable.block();
      }
      mNewFrameAvailable.close();
      mFirstFrame = false;
    }

    mSurfaceTexture.updateTexImage();

    mSurfaceTexture.getTransformMatrix(mFrameTransform);
    Matrix.multiplyMM(
        mMappedCoords, 0,
        mFrameTransform, 0,
        mSourceCoords, 0);
    mFrameExtractor.setSourceRegion(
        mMappedCoords[0], mMappedCoords[1],
        mMappedCoords[4], mMappedCoords[5],
        mMappedCoords[8], mMappedCoords[9],
        mMappedCoords[12], mMappedCoords[13]);
    // Next, render to output
    Frame output = context.getFrameManager().newFrame(mOutputFormat);
    mFrameExtractor.process(mMediaFrame, output);

    output.setTimestamp(mSurfaceTexture.getTimestamp());

    pushOutput("video", output);
    output.release();
  }
 public synchronized RawTexture get() {
   if (mCancelled) return null;
   else if (mResultReady.block(TIMEOUT)) return mTexture;
   else {
     mCancelled = true;
     return null;
   }
 }
  @SmallTest
  @Feature({"Cronet"})
  public void testInitTwoEnginesSimultaneously() throws Exception {
    final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();

    // Threads will block on runBlocker to ensure simultaneous execution.
    ConditionVariable runBlocker = new ConditionVariable(false);
    RequestThread thread1 = new RequestThread(activity, TEST_URL, runBlocker);
    RequestThread thread2 = new RequestThread(activity, URL_404, runBlocker);

    thread1.start();
    thread2.start();
    runBlocker.open();
    thread1.join();
    thread2.join();
    assertEquals(200, thread1.mListener.mResponseInfo.getHttpStatusCode());
    assertEquals(404, thread2.mListener.mResponseInfo.getHttpStatusCode());
  }
 @Override
 public void run() {
   mRunBlocker.block();
   CronetEngine cronetEngine = mActivity.initCronetEngine();
   mListener = new TestUrlRequestListener();
   UrlRequest.Builder urlRequestBuilder =
       new UrlRequest.Builder(mUrl, mListener, mListener.getExecutor(), cronetEngine);
   urlRequestBuilder.build().start();
   mListener.blockForDone();
 }
 private void startAlert(Alarm alarm) {
   // TODO 勝手にアラートが停止するようなら、foregroundにすることを検討。
   // foregroundにする場合は目的地到着のNotificationもここで行うべきか。
   // APIではonStartCommand()の間はforegroundと定義されているので問題ない
   // はずだが。Vibratorのスレッドまで停止されることがあるかもしれない。
   // startForeground(id, notification);
   // stopForeground(removeNotification);
   mCondition.close();
   vibrate(alarm);
   Log.d(TAG, "Started the alert.: " + alarm.dump());
 }
 @Override
 public void open(FilterContext context) {
   if (mLogVerbose) Log.v(TAG, "Opening SurfaceTextureSource");
   // Create SurfaceTexture anew each time - it can use substantial memory.
   mSurfaceTexture = new SurfaceTexture(mMediaFrame.getTextureId());
   // Connect SurfaceTexture to callback
   mSurfaceTexture.setOnFrameAvailableListener(onFrameAvailableListener);
   // Connect SurfaceTexture to source
   mSourceListener.onSurfaceTextureSourceReady(mSurfaceTexture);
   mFirstFrame = true;
   mNewFrameAvailable.close();
 }
  @SmallTest
  @Feature({"Cronet"})
  public void testShutdownDuringInit() throws Exception {
    final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
    final ConditionVariable block = new ConditionVariable(false);

    // Post a task to main thread to block until shutdown is called to test
    // scenario when shutdown is called right after construction before
    // context is fully initialized on the main thread.
    Runnable blockingTask =
        new Runnable() {
          public void run() {
            try {
              block.block();
            } catch (Exception e) {
              fail("Caught " + e.getMessage());
            }
          }
        };
    // Ensure that test is not running on the main thread.
    assertTrue(Looper.getMainLooper() != Looper.myLooper());
    new Handler(Looper.getMainLooper()).post(blockingTask);

    // Create new request context, but its initialization on the main thread
    // will be stuck behind blockingTask.
    final CronetEngine cronetEngine = activity.initCronetEngine();
    // Unblock the main thread, so context gets initialized and shutdown on
    // it.
    block.open();
    // Shutdown will wait for init to complete on main thread.
    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());
    }
  }
  @SmallTest
  @Feature({"Cronet"})
  public void testNoErrorWhenCanceledDuringStart() throws Exception {
    TestUrlRequestCallback callback = new TestUrlRequestCallback();
    UrlRequest.Builder builder =
        new UrlRequest.Builder(
            NativeTestServer.getEchoBodyURL(),
            callback,
            callback.getExecutor(),
            mTestFramework.mCronetEngine);
    final ConditionVariable first = new ConditionVariable();
    final ConditionVariable second = new ConditionVariable();
    builder.addHeader("Content-Type", "useless/string");
    builder.setUploadDataProvider(
        new UploadDataProvider() {
          @Override
          public long getLength() throws IOException {
            first.open();
            second.block();
            return 0;
          }

          @Override
          public void read(UploadDataSink uploadDataSink, ByteBuffer byteBuffer)
              throws IOException {}

          @Override
          public void rewind(UploadDataSink uploadDataSink) throws IOException {}
        },
        callback.getExecutor());
    UrlRequest urlRequest = builder.build();
    urlRequest.start();
    first.block();
    urlRequest.cancel();
    second.open();
    callback.blockForDone();
    assertTrue(callback.mOnCanceledCalled);
  }
  @SmallTest
  @Feature({"Cronet"})
  public void testNoErrorWhenExceptionDuringStart() throws Exception {
    TestUrlRequestCallback callback = new TestUrlRequestCallback();
    UrlRequest.Builder builder =
        new UrlRequest.Builder(
            NativeTestServer.getEchoBodyURL(),
            callback,
            callback.getExecutor(),
            mTestFramework.mCronetEngine);
    final ConditionVariable first = new ConditionVariable();
    final String exceptionMessage = "Bad Length";
    builder.addHeader("Content-Type", "useless/string");
    builder.setUploadDataProvider(
        new UploadDataProvider() {
          @Override
          public long getLength() throws IOException {
            first.open();
            throw new IOException(exceptionMessage);
          }

          @Override
          public void read(UploadDataSink uploadDataSink, ByteBuffer byteBuffer)
              throws IOException {}

          @Override
          public void rewind(UploadDataSink uploadDataSink) throws IOException {}
        },
        callback.getExecutor());
    UrlRequest urlRequest = builder.build();
    urlRequest.start();
    first.block();
    callback.blockForDone();
    assertFalse(callback.mOnCanceledCalled);
    assertEquals(UrlRequestError.LISTENER_EXCEPTION_THROWN, callback.mError.getErrorCode());
    assertEquals("Exception received from UploadDataProvider", callback.mError.getMessage());
    assertEquals(exceptionMessage, callback.mError.getCause().getMessage());
  }
 public void run() {
   while (run_flg) {
     long when = System.currentTimeMillis();
     Notification notification = new Notification(icon, tickerText, when);
     CharSequence contentTitle = "My notification";
     CharSequence contentText = "Hello World! " + i;
     PendingIntent contentIntent =
         PendingIntent.getActivity(PushSearvice.this, 0, notificationIntent, 0);
     notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
     mNotificationManager.notify(1, notification);
     mCondition.block(WAIT_TIME);
     i++;
   }
 }
Exemple #20
0
  // Being attached by an Activity
  @Override
  public void onAttach(Activity activity) {
    Log.d(TAG, "onAttach");
    super.onAttach(activity);

    mActivity = activity;
    mCallback = (TaskResultListener) activity;
    mActivityCond.open();

    if (mTaskStarted) {
      mProgDialog = mAsyncTask.createProgressDialog(mActivity);
      mAsyncTask.setProgressDialog(mProgDialog);
      mProgDialog.show();
    }
  }
Exemple #21
0
  // Being detached from the hosting activity, clean up view state
  @Override
  public void onDetach() {
    Log.d(TAG, "onDetach");
    super.onDetach();

    mActivityCond.close();
    mActivity = null;
    mCallback = null;

    mAsyncTask.setProgressDialog(null);

    if (mProgDialog != null) {
      mProgDialog.dismiss();
      mProgDialog = null;
    }
  }
 @Override
 public boolean onGLIdle(final GLCanvas canvas, final boolean renderRequested) {
   if (!mCancelled) {
     try {
       canvas.beginRenderTarget(mTexture);
       mRootPane.render(canvas);
       canvas.endRenderTarget();
     } catch (final RuntimeException e) {
       mTexture = null;
     }
   } else {
     mTexture = null;
   }
   mResultReady.open();
   return false;
 }
  @Override
  public boolean onJsPrompt(
      WebView view, String url, String message, String defaultValue, JsPromptResult r) {
    if (message != null && message.startsWith("calabash:")) {
      r.confirm("CALABASH_ACK");
      System.out.println("onJsPrompt: " + message);
      result.message = message.replace("calabash:", "");
      eventHandled.open();

      return true;
    } else {
      if (mWebChromeClient == null) {
        r.confirm("CALABASH_ERROR");
        return true;
      } else {
        return mWebChromeClient.onJsPrompt(view, url, message, defaultValue, r);
      }
    }
  }
 public void lockPreviewReadyFlag() {
   mPreviewFrameReadyForProcessing.close();
 }
 public void waitUntilOnStatusCalled() {
   mBlock.block();
   mBlock.close();
 }
 private void unlockPreviewReadyFlag() {
   mPreviewFrameReadyForProcessing.open();
 }
 public void waitUntilPreviewReady() {
   mPreviewFrameReadyForProcessing.block();
 }
Exemple #28
0
 // Method for AsyncTask to block until an Activity is attached
 protected void blockForActivity() {
   mActivityCond.block();
 }
 @Override
 public void onStatus(int status) {
   mOnStatusCalled = true;
   mStatus = status;
   mBlock.open();
 }
 public void onFrameAvailable(SurfaceTexture surfaceTexture) {
   if (mLogVerbose) Log.v(TAG, "New frame from SurfaceTexture");
   mNewFrameAvailable.open();
 }