Ejemplo n.º 1
0
  public static boolean decompressLibrary(Context context) {
    String libDir =
        context
            .getDir(XWalkLibraryInterface.PRIVATE_DATA_DIRECTORY_SUFFIX, Context.MODE_PRIVATE)
            .toString();
    File f = new File(libDir);
    if (f.exists() && f.isFile()) f.delete();
    if (!f.exists() && !f.mkdirs()) return false;

    long start = SystemClock.uptimeMillis();
    for (String library : MANDATORY_LIBRARIES) {
      try {
        Log.d(TAG, "Decompressing " + library);
        InputStream input = openRawResource(context, library);
        extractLzmaToFile(input, new File(libDir, library));
      } catch (Resources.NotFoundException e) {
        Log.d(TAG, library + " not found");
        return false;
      } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage());
        return false;
      }
    }
    Log.d(TAG, "Time to decompress : " + (SystemClock.uptimeMillis() - start) + " ms");
    return true;
  }
Ejemplo n.º 2
0
  public void halt() { // modified
    long time = SystemClock.elapsedRealtime();

    int i = 0;
    for (RegisterAgent ra : ras) {
      unregister(i);
      while (ra != null
          && ra.CurrentState != RegisterAgent.UNREGISTERED
          && SystemClock.elapsedRealtime() - time < 2000)
        try {
          Thread.sleep(100);
        } catch (InterruptedException e1) {
        }
      if (wl[i].isHeld()) {
        wl[i].release();
        if (pwl[i] != null && pwl[i].isHeld()) pwl[i].release();
      }
      if (kas[i] != null) {
        Receiver.alarm(0, LoopAlarm.class);
        kas[i].halt();
      }
      Receiver.onText(Receiver.REGISTER_NOTIFICATION + i, null, 0, 0);
      if (ra != null) ra.halt();
      if (uas[i] != null) uas[i].hangup();
      if (sip_providers[i] != null) sip_providers[i].halt();
      i++;
    }
  }
Ejemplo n.º 3
0
  @Override
  protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    Bundle extras = intent.getExtras();
    String msg = intent.getStringExtra("message");
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {

      if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
        sendNotification("Send error: " + extras.toString());
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
        sendNotification("Deleted messages on server: " + extras.toString());
        // If it's a regular GCM message, do some work.
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
        // This loop represents the service doing some work.
        for (int i = 0; i < 5; i++) {
          Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
          try {
            Thread.sleep(500);
          } catch (InterruptedException e) {
          }
        }
        Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
        // Post notification of received message.
        // sendNotification("Received: " + extras.toString());
        sendNotification(msg);
        Log.i(TAG, "Received: " + extras.toString());
      }
    }
    GcmBroadcastReciever.completeWakefulIntent(intent);
  }
  @SmallTest
  @Feature({"IntentHandling"})
  public void testUserInteraction() {
    TabRedirectHandler handler = new TabRedirectHandler(mContext);
    handler.updateIntent(sYtIntent);
    assertFalse(handler.isOnNavigation());

    handler.updateNewUrlLoading(TRANS_TYPE_OF_LINK_FROM_INTENT, false, false, 0, 0);
    assertFalse(handler.isOnEffectiveIntentRedirectChain());
    handler.updateNewUrlLoading(TRANS_TYPE_OF_LINK_FROM_INTENT, true, false, 0, 0);
    assertTrue(handler.isOnEffectiveIntentRedirectChain());
    assertFalse(handler.hasNewResolver(sMoblieYtIntent));

    assertTrue(handler.isOnNavigation());
    assertEquals(0, handler.getLastCommittedEntryIndexBeforeStartingNavigation());

    SystemClock.sleep(1);
    handler.updateNewUrlLoading(PageTransition.LINK, false, true, SystemClock.elapsedRealtime(), 1);
    assertFalse(handler.isOnEffectiveIntentRedirectChain());
    assertTrue(handler.hasNewResolver(sMoblieYtIntent));
    assertTrue(handler.hasNewResolver(sFooIntent));
    assertFalse(handler.hasNewResolver(null));

    assertTrue(handler.isOnNavigation());
    assertEquals(1, handler.getLastCommittedEntryIndexBeforeStartingNavigation());
  }
  @SmallTest
  @Feature({"IntentHandling"})
  public void testNavigationWithForwardBack() {
    TabRedirectHandler handler = new TabRedirectHandler(mContext);
    handler.updateIntent(sYtIntent);
    assertFalse(handler.isOnNavigation());
    assertFalse(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    handler.updateNewUrlLoading(
        PageTransition.FORM_SUBMIT | PageTransition.FORWARD_BACK,
        false,
        true,
        SystemClock.elapsedRealtime(),
        0);
    assertTrue(handler.shouldStayInChrome(false));
    assertTrue(handler.shouldStayInChrome(true));
    handler.updateNewUrlLoading(
        PageTransition.LINK, false, false, SystemClock.elapsedRealtime(), 1);
    assertTrue(handler.shouldStayInChrome(false));
    assertTrue(handler.shouldStayInChrome(true));

    assertTrue(handler.isOnNavigation());
    assertEquals(0, handler.getLastCommittedEntryIndexBeforeStartingNavigation());

    SystemClock.sleep(1);
    handler.updateNewUrlLoading(PageTransition.LINK, false, true, SystemClock.elapsedRealtime(), 2);
    assertFalse(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    assertTrue(handler.isOnNavigation());
    assertEquals(2, handler.getLastCommittedEntryIndexBeforeStartingNavigation());
  }
 private void m2619a(long j, JSONObject jSONObject) throws JSONException {
   int i = 1;
   boolean p = this.Cv.m1149p(j);
   int i2 = (!this.Cz.ev() || this.Cz.m1149p(j)) ? 0 : 1;
   if ((!this.CA.ev() || this.CA.m1149p(j)) && (!this.CB.ev() || this.CB.m1149p(j))) {
     i = 0;
   }
   i2 = i2 != 0 ? 2 : 0;
   if (i != 0) {
     i2 |= 1;
   }
   if (p || this.Cu == null) {
     this.Cu = new MediaStatus(jSONObject);
     this.Ct = SystemClock.elapsedRealtime();
     i2 = 7;
   } else {
     i2 = this.Cu.m108a(jSONObject, i2);
   }
   if ((i2 & 1) != 0) {
     this.Ct = SystemClock.elapsedRealtime();
     onStatusUpdated();
   }
   if ((i2 & 2) != 0) {
     this.Ct = SystemClock.elapsedRealtime();
     onStatusUpdated();
   }
   if ((i2 & 4) != 0) {
     onMetadataUpdated();
   }
   for (gr c : this.CF) {
     c.m1147c(j, 0);
   }
 }
Ejemplo n.º 7
0
  /**
   * Waits for a text to be shown.
   *
   * @param classToFilterBy the class to filter by
   * @param text the text that needs to be shown, specified as a regular expression.
   * @param expectedMinimumNumberOfMatches the minimum number of matches of text that must be shown.
   *     {@code 0} means any number of matches
   * @param timeout the amount of time in milliseconds to wait
   * @param scroll {@code true} if scrolling should be performed
   * @param onlyVisible {@code true} if only visible text views should be waited for
   * @param hardStoppage {@code true} if search is to be stopped when timeout expires
   * @return {@code true} if text is found and {@code false} if it is not found before the timeout
   */
  public <T extends TextView> T waitForText(
      Class<T> classToFilterBy,
      String text,
      int expectedMinimumNumberOfMatches,
      long timeout,
      boolean scroll,
      boolean onlyVisible,
      boolean hardStoppage) {
    final long endTime = SystemClock.uptimeMillis() + timeout;

    while (true) {
      final boolean timedOut = SystemClock.uptimeMillis() > endTime;
      if (timedOut) {
        return null;
      }

      sleeper.sleep();

      if (!hardStoppage) timeout = 0;

      final T textViewToReturn =
          searcher.searchFor(
              classToFilterBy, text, expectedMinimumNumberOfMatches, timeout, scroll, onlyVisible);

      if (textViewToReturn != null) {
        return textViewToReturn;
      }
    }
  }
Ejemplo n.º 8
0
  @Override
  protected synchronized void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Drawable d = mCurrentDrawable;
    if (d != null) {
      // Translate canvas so a indeterminate circular progress bar with padding
      // rotates properly in its animation
      canvas.save();
      canvas.translate(mPaddingLeft, mPaddingTop);
      long time = getDrawingTime();
      if (mAnimation != null) {
        mAnimation.getTransformation(time, mTransformation);
        float scale = mTransformation.getAlpha();
        try {
          mInDrawing = true;
          d.setLevel((int) (scale * MAX_LEVEL));
        } finally {
          mInDrawing = false;
        }
        if (SystemClock.uptimeMillis() - mLastDrawTime >= ANIMATION_RESOLUTION) {
          mLastDrawTime = SystemClock.uptimeMillis();
          postInvalidateDelayed(ANIMATION_RESOLUTION);
        }
      }
      d.draw(canvas);
      canvas.restore();
      if (mShouldStartAnimationDrawable && d instanceof Animatable) {
        ((Animatable) d).start();
        mShouldStartAnimationDrawable = false;
      }
    }
  }
Ejemplo n.º 9
0
 /**
  * Sends over the unix username and password if the appropriate option is enabled, in order to
  * automatically authenticate to x11vnc when it asks for unix credentials (-unixpw).
  */
 void sendUnixAuth() {
   // If the type of connection is ssh-tunneled and we are told to send the unix credentials, then
   // do so.
   // Do not send the up event if this is a bb10 device, since the up-event hack in
   // processLocalKeyEvent takes care of that...
   if (connection.getConnectionType() == VncConstants.CONN_TYPE_SSH
       && connection.getAutoXUnixAuth()) {
     keyboard.processLocalKeyEvent(
         KeyEvent.KEYCODE_UNKNOWN,
         new KeyEvent(SystemClock.uptimeMillis(), connection.getSshUser(), 0, 0));
     keyboard.processLocalKeyEvent(
         KeyEvent.KEYCODE_ENTER, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
     if (!bb10)
       keyboard.processLocalKeyEvent(
           KeyEvent.KEYCODE_ENTER, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER));
     keyboard.processLocalKeyEvent(
         KeyEvent.KEYCODE_UNKNOWN,
         new KeyEvent(SystemClock.uptimeMillis(), connection.getSshPassword(), 0, 0));
     keyboard.processLocalKeyEvent(
         KeyEvent.KEYCODE_ENTER, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
     if (!bb10)
       keyboard.processLocalKeyEvent(
           KeyEvent.KEYCODE_ENTER, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER));
   }
 }
Ejemplo n.º 10
0
  private void calcSpeed(long sofar) {
    if (minIntervalUpdateSpeed <= 0) {
      return;
    }

    boolean isUpdateData = false;
    do {
      if (lastCalcSpeedSofarTime == 0) {
        isUpdateData = true;
        break;
      }

      long interval = SystemClock.uptimeMillis() - lastCalcSpeedSofarTime;
      if (interval >= minIntervalUpdateSpeed || (speed == 0 && interval > 0)) {
        speed = (int) ((sofar - lastCalcSpeedSofar) / interval);
        speed = Math.max(0, speed);
        isUpdateData = true;
        break;
      }
    } while (false);

    if (isUpdateData) {
      lastCalcSpeedSofar = sofar;
      lastCalcSpeedSofarTime = SystemClock.uptimeMillis();
    }
  }
Ejemplo n.º 11
0
 /**
  * Simulate touching a specific location and dragging to a new location.
  *
  * <p>This method was copied from {@code TouchUtils.java} in the Android Open Source Project, and
  * modified here.
  *
  * @param fromX X coordinate of the initial touch, in screen coordinates
  * @param toX Xcoordinate of the drag destination, in screen coordinates
  * @param fromY X coordinate of the initial touch, in screen coordinates
  * @param toY Y coordinate of the drag destination, in screen coordinates
  * @param stepCount How many move steps to include in the drag
  */
 public void drag(float fromX, float toX, float fromY, float toY, int stepCount) {
   long downTime = SystemClock.uptimeMillis();
   long eventTime = SystemClock.uptimeMillis();
   float y = fromY;
   float x = fromX;
   float yStep = (toY - fromY) / stepCount;
   float xStep = (toX - fromX) / stepCount;
   MotionEvent event =
       MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, fromX, fromY, 0);
   try {
     inst.sendPointerSync(event);
   } catch (SecurityException ignored) {
   }
   for (int i = 0; i < stepCount; ++i) {
     y += yStep;
     x += xStep;
     eventTime = SystemClock.uptimeMillis();
     event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, x, y, 0);
     try {
       inst.sendPointerSync(event);
     } catch (SecurityException ignored) {
     }
   }
   eventTime = SystemClock.uptimeMillis();
   event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, toX, toY, 0);
   try {
     inst.sendPointerSync(event);
   } catch (SecurityException ignored) {
   }
 }
  @Override
  protected Bitmap doInBackground(Void... params) {
    final long start = SystemClock.elapsedRealtime();

    Bitmap origin = mBitmapOriginal;
    Bitmap bitmap = BitmapUtils.doBlur(origin, 3, false);

    if (!running) {
      return null;
    }

    Canvas canvas = new Canvas(bitmap);
    canvas.drawColor(mForegroundColor);

    if (Build.DEBUG) {
      long delta = SystemClock.elapsedRealtime() - start;
      Log.d(
          TAG,
          "Dynamic background created in "
              + delta
              + " millis:"
              + " width="
              + bitmap.getWidth()
              + " height="
              + bitmap.getHeight());
    }

    return bitmap;
  }
Ejemplo n.º 13
0
 private void refreshMapInternal(DrawSettings drawSettings) {
   handler.removeMessages(MAP_REFRESH_MESSAGE);
   SurfaceHolder holder = getHolder();
   long ms = SystemClock.elapsedRealtime();
   synchronized (holder) {
     Canvas canvas = holder.lockCanvas();
     if (canvas != null) {
       try {
         final float ratioy = mapPosition == OsmandSettings.BOTTOM_CONSTANT ? 0.8f : 0.5f;
         final int cy = (int) (ratioy * getHeight());
         if (currentViewport.getPixWidth() != getWidth()
             || currentViewport.getPixHeight() != getHeight()
             || currentViewport.getCenterPixelY() != cy) {
           currentViewport.setPixelDimensions(getWidth(), getHeight(), 0.5f, ratioy);
           refreshBufferImage(drawSettings);
         }
         // make copy to avoid concurrency
         RotatedTileBox viewportToDraw = currentViewport.copy();
         fillCanvas(canvas, drawSettings);
         drawOverMap(canvas, viewportToDraw, drawSettings);
       } finally {
         holder.unlockCanvasAndPost(canvas);
       }
     }
     if (MEASURE_FPS) {
       main.calculateFPS(ms, SystemClock.elapsedRealtime());
     }
   }
 }
  /**
   * Waits up to a given bound for a result of a request and returns it.
   *
   * @param interactionId The interaction id to match the result with the request.
   * @return Whether the result was received.
   */
  private boolean waitForResultTimedLocked(int interactionId) {
    long waitTimeMillis = TIMEOUT_INTERACTION_MILLIS;
    final long startTimeMillis = SystemClock.uptimeMillis();
    while (true) {
      try {
        Message sameProcessMessage = getSameProcessMessageAndClear();
        if (sameProcessMessage != null) {
          sameProcessMessage.getTarget().handleMessage(sameProcessMessage);
        }

        if (mInteractionId == interactionId) {
          return true;
        }
        if (mInteractionId > interactionId) {
          return false;
        }
        final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
        waitTimeMillis = TIMEOUT_INTERACTION_MILLIS - elapsedTimeMillis;
        if (waitTimeMillis <= 0) {
          return false;
        }
        mInstanceLock.wait(waitTimeMillis);
      } catch (InterruptedException ie) {
        /* ignore */
      }
    }
  }
 /** Execute a request without applying and rewrite rules. */
 public HttpResponse executeWithoutRewriting(HttpUriRequest request, HttpContext context)
     throws IOException {
   String code = "Error";
   long start = SystemClock.elapsedRealtime();
   try {
     HttpResponse response = mClient.execute(request, context);
     code = Integer.toString(response.getStatusLine().getStatusCode());
     return response;
   } catch (IOException e) {
     code = "IOException";
     throw e;
   } finally {
     // Record some statistics to the checkin service about the outcome.
     // Note that this is only describing execute(), not body download.
     try {
       long elapsed = SystemClock.elapsedRealtime() - start;
       ContentValues values = new ContentValues();
       values.put(
           Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_STATUS + ":" + mUserAgent + ":" + code);
       values.put(Checkin.Stats.COUNT, 1);
       values.put(Checkin.Stats.SUM, elapsed / 1000.0);
       mResolver.insert(Checkin.Stats.CONTENT_URI, values);
     } catch (Exception e) {
       Log.e(TAG, "Error recording stats", e);
     }
   }
 }
Ejemplo n.º 16
0
  public synchronized void onDrawFrame(GL10 gl) {
    if (ENABLE_FPS_TEST) {
      long now = System.nanoTime();
      if (mFrameCountingStart == 0) {
        mFrameCountingStart = now;
      } else if ((now - mFrameCountingStart) > 1000000000) {
        Log.v(TAG, "fps: " + (double) mFrameCount * 1000000000 / (now - mFrameCountingStart));
        mFrameCountingStart = now;
        mFrameCount = 0;
      }
      ++mFrameCount;
    }

    if ((mFlags & FLAG_NEED_LAYOUT) != 0) layoutContentPane();
    clearClip();
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_STENCIL_BUFFER_BIT);
    gl.glEnable(GL11.GL_BLEND);
    gl.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);

    mAnimationTime = SystemClock.uptimeMillis();
    if (mContentView != null) {
      mContentView.render(GLRootView.this, (GL11) gl);
    }
    long now = SystemClock.uptimeMillis();
    for (Animation animation : mAnimations) {
      animation.setStartTime(now);
    }
    mAnimations.clear();
  }
Ejemplo n.º 17
0
 protected Long doInBackground(Object... objects) {
   Long startTime = SystemClock.elapsedRealtime();
   calculatePi();
   Long endTime = SystemClock.elapsedRealtime();
   accumulatedRunTime += (endTime - startTime);
   return (long) 0;
 }
Ejemplo n.º 18
0
  /**
   * The statistics - it is called every cycle, it checks if time since last store is greater than
   * the statistics gathering period (1 sec) and if so it calculates the FPS for the last period and
   * stores it.
   *
   * <p>It tracks the number of frames per period. The number of frames since the start of the
   * period are summed up and the calculation takes part only if the next period and the frame count
   * is reset to 0.
   */
  private void storeStats() {
    frameCountPerStatCycle++;
    totalFrameCount++;
    // assuming that the sleep works each call to storeStats
    // happens at 1000/FPS so we just add it up
    // statusIntervalTimer += FRAME_PERIOD;

    // check the actual time
    statusIntervalTimer += (SystemClock.uptimeMillis() - statusIntervalTimer);

    if (statusIntervalTimer >= lastStatusStore + STAT_INTERVAL) {
      // calculate the actual frames pers status check interval
      double actualFps = (double) (frameCountPerStatCycle);

      // stores the latest fps in the array
      fpsStore[(int) statsCount % FPS_HISTORY_NR] = actualFps;

      // increase the number of times statistics was calculated
      statsCount++;

      // saving the number of total frames skipped
      totalFramesSkipped += framesSkippedPerStatCycle;
      // resetting the counters after a status record (1 sec)
      framesSkippedPerStatCycle = 0;
      statusIntervalTimer = 0;
      frameCountPerStatCycle = 0;

      statusIntervalTimer = SystemClock.uptimeMillis();
      lastStatusStore = statusIntervalTimer;
      // Log.d(TAG, "Average FPS:" + df.format(averageFps));
    }
  }
Ejemplo n.º 19
0
  /**
   * Waits for a given view.
   *
   * @param view the view to wait for
   * @param timeout the amount of time in milliseconds to wait
   * @param scroll {@code true} if scrolling should be performed
   * @param checkIsShown {@code true} if view.isShown() should be used
   * @return {@code true} if view is shown and {@code false} if it is not shown before the timeout
   */
  public View waitForView(View view, int timeout, boolean scroll, boolean checkIsShown) {
    long endTime = SystemClock.uptimeMillis() + timeout;
    int retry = 0;

    if (view == null) return null;

    while (SystemClock.uptimeMillis() < endTime) {

      final boolean foundAnyMatchingView = searcher.searchFor(view);

      if (checkIsShown && foundAnyMatchingView && !view.isShown()) {
        sleeper.sleepMini();
        retry++;

        View identicalView = viewFetcher.getIdenticalView(view);
        if (identicalView != null && !view.equals(identicalView)) {
          view = identicalView;
        }

        if (retry > 5) {
          return view;
        }
        continue;
      }

      if (foundAnyMatchingView) {
        return view;
      }

      if (scroll) scroller.scrollDown();

      sleeper.sleep();
    }
    return view;
  }
Ejemplo n.º 20
0
 @VisibleForTesting
 protected void sendSyntheticKeyPress(int keyCode, int flags) {
   long eventTime = SystemClock.uptimeMillis();
   sendKeyEvent(
       new KeyEvent(
           eventTime,
           eventTime,
           KeyEvent.ACTION_DOWN,
           keyCode,
           0,
           0,
           KeyCharacterMap.VIRTUAL_KEYBOARD,
           0,
           flags));
   sendKeyEvent(
       new KeyEvent(
           SystemClock.uptimeMillis(),
           eventTime,
           KeyEvent.ACTION_UP,
           keyCode,
           0,
           0,
           KeyCharacterMap.VIRTUAL_KEYBOARD,
           0,
           flags));
 }
Ejemplo n.º 21
0
  /**
   * Waits for and returns a View.
   *
   * @param index the index of the view
   * @param classToFilterby the class to filter
   * @return the specified View
   */
  public <T extends View> T waitForAndGetView(int index, Class<T> classToFilterBy) {
    long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
    while (SystemClock.uptimeMillis() <= endTime
        && !waitForView(classToFilterBy, index, true, true)) ;
    int numberOfUniqueViews = searcher.getNumberOfUniqueViews();
    ArrayList<T> views =
        RobotiumUtils.removeInvisibleViews(viewFetcher.getCurrentViews(classToFilterBy));

    if (views.size() < numberOfUniqueViews) {
      int newIndex = index - (numberOfUniqueViews - views.size());
      if (newIndex >= 0) index = newIndex;
    }

    T view = null;
    try {
      view = views.get(index);
    } catch (IndexOutOfBoundsException exception) {
      int match = index + 1;
      if (match > 1) {
        Assert.fail(match + " " + classToFilterBy.getSimpleName() + "s" + " are not found!");
      } else {
        Assert.fail(classToFilterBy.getSimpleName() + " is not found!");
      }
    }
    views = null;
    return view;
  }
  @LargeTest
  public void testPerformAccessibilityActionClearSelection() throws Exception {
    final long startTimeMillis = SystemClock.uptimeMillis();
    try {
      // find a view and make sure it is not selected
      AccessibilityNodeInfo button =
          mUiTestAutomationBridge.findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5);
      assertFalse(button.isSelected());

      // select the view
      assertTrue(button.performAction(ACTION_SELECT));

      // find the view again and make sure it is selected
      button =
          mUiTestAutomationBridge.findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5);
      assertTrue(button.isSelected());

      // unselect the view
      assertTrue(button.performAction(ACTION_CLEAR_SELECTION));

      // find the view again and make sure it is not selected
      button =
          mUiTestAutomationBridge.findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5);
      assertFalse(button.isSelected());
    } finally {
      if (DEBUG) {
        final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
        Log.i(LOG_TAG, "testPerformAccessibilityActionClearSelection: " + elapsedTimeMillis + "ms");
      }
    }
  }
  @SmallTest
  @Feature({"IntentHandling"})
  public void testIntentHavingChromePackageName() {
    TabRedirectHandler handler = new TabRedirectHandler(mContext);
    Intent fooIntent = new Intent(sFooIntent);
    fooIntent.setPackage(TEST_PACKAGE_NAME);
    handler.updateIntent(fooIntent);
    assertFalse(handler.isOnNavigation());
    assertTrue(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    handler.updateNewUrlLoading(TRANS_TYPE_OF_LINK_FROM_INTENT, false, false, 0, 0);
    assertTrue(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));
    handler.updateNewUrlLoading(PageTransition.LINK, false, false, 0, 1);
    assertTrue(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    assertTrue(handler.isOnNavigation());
    assertEquals(0, handler.getLastCommittedEntryIndexBeforeStartingNavigation());

    SystemClock.sleep(1);
    handler.updateNewUrlLoading(PageTransition.LINK, false, true, SystemClock.elapsedRealtime(), 2);
    assertFalse(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    assertTrue(handler.isOnNavigation());
    assertEquals(2, handler.getLastCommittedEntryIndexBeforeStartingNavigation());
  }
 @LargeTest
 public void testObjectContract() throws Exception {
   final long startTimeMillis = SystemClock.uptimeMillis();
   try {
     // find a view and make sure it is not focused
     AccessibilityNodeInfo button =
         mUiTestAutomationBridge.findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5);
     assertNotNull(button);
     AccessibilityNodeInfo parent = button.getParent();
     final int childCount = parent.getChildCount();
     for (int i = 0; i < childCount; i++) {
       AccessibilityNodeInfo child = parent.getChild(i);
       assertNotNull(child);
       if (child.equals(button)) {
         assertEquals(
             "Equal objects must have same hasCode.", button.hashCode(), child.hashCode());
         return;
       }
     }
     fail("Parent's children do not have the info whose parent is the parent.");
   } finally {
     if (DEBUG) {
       final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
       Log.i(LOG_TAG, "testObjectContract: " + elapsedTimeMillis + "ms");
     }
   }
 }
Ejemplo n.º 25
0
  @Override
  public void initData() {
    long startTime = SystemClock.currentThreadTimeMillis();

    //        ApiManager.getObGithub(new MyObserver<List<GithubCollect>>() {
    //            @Override
    //            public void onNext(List<GithubCollect> datas) {
    //                Logger.d(datas);
    //            }
    //        });

    saveCache();

    long endTime = SystemClock.currentThreadTimeMillis();
    long d = endTime - startTime;

    if (d > TIME_OUT) {
      Intent intent = new Intent(SplashActivity.this, MainActivity.class);
      startActivity(intent);
      finish();
    } else {
      new Handler()
          .postDelayed(
              new Runnable() {
                @Override
                public void run() {
                  Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                  startActivity(intent);
                  finish();
                }
              },
              TIME_OUT - d);
    }
  }
  @LargeTest
  public void testGetRootAccessibilityNodeInfoInActiveWindow() throws Exception {
    final long startTimeMillis = SystemClock.uptimeMillis();
    try {
      // get the root via the designated API
      AccessibilityNodeInfo fetched =
          mUiTestAutomationBridge.getRootAccessibilityNodeInfoInActiveWindow();
      assertNotNull(fetched);

      // get the root via traversal
      AccessibilityNodeInfo expected =
          mUiTestAutomationBridge.findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.root);
      while (true) {
        AccessibilityNodeInfo parent = expected.getParent();
        if (parent == null) {
          break;
        }
        expected = parent;
      }
      assertNotNull(expected);

      assertEquals("The node with id \"root\" should be the root.", expected, fetched);
    } finally {
      if (DEBUG) {
        final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
        Log.i(
            LOG_TAG, "testGetRootAccessibilityNodeInfoInActiveWindow: " + elapsedTimeMillis + "ms");
      }
    }
  }
  /**
   * Verify that LONG_TAP is triggered after LongPress followed by an UP.
   *
   * @throws Exception
   */
  @SmallTest
  @Feature({"Gestures"})
  public void testGestureLongTap() throws Exception {
    final long downTime = SystemClock.uptimeMillis();
    final long eventTime = SystemClock.uptimeMillis();

    GestureRecordingMotionEventDelegate mockDelegate = new GestureRecordingMotionEventDelegate();
    mGestureHandler =
        new ContentViewGestureHandler(
            getInstrumentation().getTargetContext(),
            mockDelegate,
            new MockZoomManager(getInstrumentation().getTargetContext(), null));
    mLongPressDetector = mGestureHandler.getLongPressDetector();

    MotionEvent event = motionEvent(MotionEvent.ACTION_DOWN, downTime, downTime);
    assertTrue(mGestureHandler.onTouchEvent(event));
    assertNotNull(mockDelegate.getMostRecentGestureEvent());
    assertTrue("Should have a pending LONG_PRESS", mLongPressDetector.hasPendingMessage());

    mLongPressDetector.sendLongPressGestureForTest();

    assertEquals(
        "A LONG_PRESS gesture should have been sent",
        ContentViewGestureHandler.GESTURE_LONG_PRESS,
        mockDelegate.mMostRecentGestureEvent.mType);

    event = motionEvent(MotionEvent.ACTION_UP, downTime, eventTime + 1000);
    assertTrue(mGestureHandler.onTouchEvent(event));
    assertEquals(
        "A LONG_TAP gesture should have been sent",
        ContentViewGestureHandler.GESTURE_LONG_TAP,
        mockDelegate.mMostRecentGestureEvent.mType);
  }
Ejemplo n.º 28
0
  @Override
  public void click() {
    String tagName = getTagName();
    if (tagName != null && "OPTION".equals(tagName.toUpperCase())) {
      driver.resetPageIsLoading();
      driver.executeAtom(AndroidAtoms.CLICK, this);
      driver.waitForPageToLoad();
    }

    Point center = getCenterCoordinates();
    long downTime = SystemClock.uptimeMillis();
    final List<MotionEvent> events = Lists.newArrayList();

    MotionEvent downEvent =
        MotionEvent.obtain(
            downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, center.x, center.y, 0);
    events.add(downEvent);
    MotionEvent upEvent =
        MotionEvent.obtain(
            downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, center.x, center.y, 0);

    events.add(upEvent);

    driver.resetPageIsLoading();
    Activity current = ServerInstrumentation.getInstance().getCurrentActivity();
    EventSender.sendMotion(events, webview, current);

    // If the page started loading we should wait
    // until the page is done loading.
    driver.waitForPageToLoad();
  }
  private void updateWave() {
    float progress =
        Math.min(1f, (float) (SystemClock.uptimeMillis() - mStartTime) / mRippleAnimDuration);

    if (mState != STATE_RELEASE) {
      setRippleEffect(
          mRipplePoint.x,
          mRipplePoint.y,
          mMaxRippleRadius * mInInterpolator.getInterpolation(progress));

      if (progress == 1f) {
        mStartTime = SystemClock.uptimeMillis();
        if (mState == STATE_PRESS) setRippleState(STATE_HOVER);
        else {
          setRippleEffect(mRipplePoint.x, mRipplePoint.y, 0);
          setRippleState(STATE_RELEASE);
        }
      }
    } else {
      setRippleEffect(
          mRipplePoint.x,
          mRipplePoint.y,
          mMaxRippleRadius * mOutInterpolator.getInterpolation(progress));

      if (progress == 1f) setRippleState(STATE_OUT);
    }

    if (isRunning()) scheduleSelf(mUpdater, SystemClock.uptimeMillis() + ViewUtil.FRAME_DURATION);

    invalidateSelf();
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
      if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
        sendNotification("Send error: " + extras.toString());
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
        sendNotification("Deleted messages on server: " + extras.toString());
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

        for (int i = 0; i < 3; i++) {
          Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
          try {
            Thread.sleep(5000);
          } catch (InterruptedException e) {
          }
        }
        Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

        sendNotification(
            "Message Received from Google GCM Server: " + extras.get(Config.MESSAGE_KEY));
        Log.i(TAG, "Received: " + extras.toString());
      }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
  }