com.facebook.react.common.SystemClock Java Examples

The following examples show how to use com.facebook.react.common.SystemClock. 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: ReactViewPager.java    From react-native-image-zoom with MIT License 6 votes vote down vote up
@Override
public void onPageScrollStateChanged(int state) {
    String pageScrollState;
    switch (state) {
        case SCROLL_STATE_IDLE:
            pageScrollState = "idle";
            break;
        case SCROLL_STATE_DRAGGING:
            pageScrollState = "dragging";
            break;
        case SCROLL_STATE_SETTLING:
            pageScrollState = "settling";
            break;
        default:
            throw new IllegalStateException("Unsupported pageScrollState");
    }
    mEventDispatcher.dispatchEvent(
            new PageScrollStateChangedEvent(getId(), SystemClock.nanoTime(), pageScrollState));
}
 
Example #2
Source File: RNFusedLocationModule.java    From react-native-geolocation-service with MIT License 5 votes vote down vote up
/**
 * Get last known location if it exists, otherwise request a new update.
 */
private void getUserLocation() {
  if (mFusedProviderClient != null) {
    mFusedProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
      @Override
      public void onComplete(@NonNull Task<Location> task) {
        Location location = null;

        try {
          location = task.getResult(ApiException.class);
        } catch (ApiException exception) {
          Log.w(TAG, "getLastLocation error: " + exception.getMessage());
        }

        if (location != null &&
          (SystemClock.currentTimeMillis() - location.getTime()) < mMaximumAge) {
          invokeSuccess(LocationUtils.locationToMap(location), true);
          return;
        }

        // Last location is not available, request location update.
        new SingleLocationUpdate(
          mFusedProviderClient,
          mLocationRequest,
          mTimeout,
          mSuccessCallback,
          mErrorCallback
        ).getLocation();
      }
    });
  }
}
 
Example #3
Source File: LocationModule.java    From react-native-GPay with MIT License 5 votes vote down vote up
/**
 * Get the current position. This can return almost immediately if the location is cached or
 * request an update, which might take a while.
 *
 * @param options map containing optional arguments: timeout (millis), maximumAge (millis) and
 *        highAccuracy (boolean)
 */
@ReactMethod
public void getCurrentPosition(
    ReadableMap options,
    final Callback success,
    Callback error) {
  LocationOptions locationOptions = LocationOptions.fromReactMap(options);

  try {
    LocationManager locationManager =
        (LocationManager) getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    String provider = getValidProvider(locationManager, locationOptions.highAccuracy);
    if (provider == null) {
      error.invoke(
          PositionError.buildError(
              PositionError.POSITION_UNAVAILABLE, "No location provider available."));
      return;
    }
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null && (SystemClock.currentTimeMillis() - location.getTime()) < locationOptions.maximumAge) {
      success.invoke(locationToMap(location));
      return;
    }

    new SingleUpdateRequest(locationManager, provider, locationOptions.timeout, success, error)
        .invoke(location);
  } catch (SecurityException e) {
    throwLocationPermissionMissing(e);
  }
}
 
Example #4
Source File: Timing.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Override
public void run() {
  if (mCancelled) {
    return;
  }

  long frameTimeMillis = mFrameStartTime / 1000000;
  long timeSinceBoot = SystemClock.uptimeMillis();
  long frameTimeElapsed = timeSinceBoot - frameTimeMillis;
  long time = SystemClock.currentTimeMillis();
  long absoluteFrameStartTime = time - frameTimeElapsed;

  if (FRAME_DURATION_MS - (float) frameTimeElapsed < IDLE_CALLBACK_FRAME_DEADLINE_MS) {
    return;
  }

  boolean sendIdleEvents;
  synchronized (mIdleCallbackGuard) {
    sendIdleEvents = mSendIdleEvents;
  }

  if (sendIdleEvents) {
    getReactApplicationContext().getJSModule(JSTimers.class)
        .callIdleCallbacks(absoluteFrameStartTime);
  }

  mCurrentIdleCallbackRunnable = null;
}
 
Example #5
Source File: Timing.java    From react-native-GPay with MIT License 5 votes vote down vote up
@ReactMethod
public void createTimer(
    final int callbackID,
    final int duration,
    final double jsSchedulingTime,
    final boolean repeat) {
  long deviceTime = SystemClock.currentTimeMillis();
  long remoteTime = (long) jsSchedulingTime;

  // If the times on the server and device have drifted throw an exception to warn the developer
  // that things might not work or results may not be accurate. This is required only for
  // developer builds.
  if (mDevSupportManager.getDevSupportEnabled()) {
    long driftTime = Math.abs(remoteTime - deviceTime);
    if (driftTime > 60000) {
      getReactApplicationContext().getJSModule(JSTimers.class)
        .emitTimeDriftWarning(
          "Debugger and device times have drifted by more than 60s. Please correct this by " +
          "running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine.");
    }
  }

  // Adjust for the amount of time it took for native to receive the timer registration call
  long adjustedDuration = Math.max(0, remoteTime - deviceTime + duration);
  if (duration == 0 && !repeat) {
    WritableArray timerToCall = Arguments.createArray();
    timerToCall.pushInt(callbackID);
    getReactApplicationContext().getJSModule(JSTimers.class)
      .callTimers(timerToCall);
    return;
  }

  long initialTargetTime = SystemClock.nanoTime() / 1000000 + adjustedDuration;
  Timer timer = new Timer(callbackID, initialTargetTime, duration, repeat);
  synchronized (mTimerGuard) {
    mTimers.add(timer);
    mTimerIdsToTimers.put(callbackID, timer);
  }
}
 
Example #6
Source File: TimingModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
private void stepChoreographerFrame() {
  ChoreographerCompat.FrameCallback callback = mPostFrameCallbackHandler.getAndResetFrameCallback();
  ChoreographerCompat.FrameCallback idleCallback = mIdlePostFrameCallbackHandler.getAndResetFrameCallback();

  mCurrentTimeNs += FRAME_TIME_NS;
  when(SystemClock.uptimeMillis()).thenReturn(mCurrentTimeNs / 1000000);
  if (callback != null) {
    callback.doFrame(mCurrentTimeNs);
  }

  if (idleCallback != null) {
    idleCallback.doFrame(mCurrentTimeNs);
  }
}
 
Example #7
Source File: TimingModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testIdleCallback() {
  mTiming.onHostResume();
  mTiming.setSendIdleEvents(true);

  stepChoreographerFrame();
  verify(mJSTimersMock).callIdleCallbacks(SystemClock.currentTimeMillis());
}
 
Example #8
Source File: RCTCaptureManager.java    From react-native-smart-barcode with MIT License 5 votes vote down vote up
@Override
protected void addEventEmitters(
        final ThemedReactContext reactContext,
        final CaptureView view) {
    view.setOnEvChangeListener(
            new CaptureView.OnEvChangeListener() {
                @Override
                public void getQRCodeResult(String result,BarcodeFormat format) {
                    reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher()
                            .dispatchEvent(new QRCodeResultEvent(view.getId(), SystemClock.nanoTime(), result,format));
                }

            });
}
 
Example #9
Source File: ReactViewPager.java    From react-native-image-zoom with MIT License 5 votes vote down vote up
@Override
public void onPageSelected(int position) {
    if (!mIsCurrentItemFromJs) {
        mEventDispatcher.dispatchEvent(
                new PageSelectedEvent(getId(), SystemClock.nanoTime(), position));
    }
}
 
Example #10
Source File: Event.java    From react-native-GPay with MIT License 4 votes vote down vote up
/**
 * This method needs to be called before event is sent to event dispatcher.
 */
protected void init(int viewTag) {
  mViewTag = viewTag;
  mTimestampMs = SystemClock.uptimeMillis();
  mInitialized = true;
}
 
Example #11
Source File: RootViewTest.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Test
public void testTouchEmitter() {
  ReactInstanceManager instanceManager = mock(ReactInstanceManager.class);
  when(instanceManager.getCurrentReactContext()).thenReturn(mReactContext);

  UIManagerModule uiManager = mock(UIManagerModule.class);
  EventDispatcher eventDispatcher = mock(EventDispatcher.class);
  RCTEventEmitter eventEmitterModuleMock = mock(RCTEventEmitter.class);
  when(mCatalystInstanceMock.getNativeModule(UIManagerModule.class))
      .thenReturn(uiManager);
  when(uiManager.getEventDispatcher()).thenReturn(eventDispatcher);

  int rootViewId = 7;

  ReactRootView rootView = new ReactRootView(mReactContext);
  rootView.setId(rootViewId);
  rootView.startReactApplication(instanceManager, "");
  rootView.simulateAttachForTesting();

  long ts = SystemClock.uptimeMillis();

  // Test ACTION_DOWN event
  rootView.onTouchEvent(
      MotionEvent.obtain(100, ts, MotionEvent.ACTION_DOWN, 0, 0, 0));

  ArgumentCaptor<Event> downEventCaptor = ArgumentCaptor.forClass(Event.class);
  verify(eventDispatcher).dispatchEvent(downEventCaptor.capture());
  verifyNoMoreInteractions(eventDispatcher);

  downEventCaptor.getValue().dispatch(eventEmitterModuleMock);

  ArgumentCaptor<JavaOnlyArray> downActionTouchesArgCaptor =
      ArgumentCaptor.forClass(JavaOnlyArray.class);
  verify(eventEmitterModuleMock).receiveTouches(
      eq("topTouchStart"),
      downActionTouchesArgCaptor.capture(),
      any(JavaOnlyArray.class));
  verifyNoMoreInteractions(eventEmitterModuleMock);

  assertThat(downActionTouchesArgCaptor.getValue().size()).isEqualTo(1);
  assertThat(downActionTouchesArgCaptor.getValue().getMap(0)).isEqualTo(
      JavaOnlyMap.of(
          "pageX",
          0.,
          "pageY",
          0.,
          "locationX",
          0.,
          "locationY",
          0.,
          "target",
          rootViewId,
          "timestamp",
          (double) ts,
          "identifier",
          0.));

  // Test ACTION_UP event
  reset(eventEmitterModuleMock, eventDispatcher);

  ArgumentCaptor<Event> upEventCaptor = ArgumentCaptor.forClass(Event.class);
  ArgumentCaptor<JavaOnlyArray> upActionTouchesArgCaptor =
      ArgumentCaptor.forClass(JavaOnlyArray.class);

  rootView.onTouchEvent(
      MotionEvent.obtain(50, ts, MotionEvent.ACTION_UP, 0, 0, 0));
  verify(eventDispatcher).dispatchEvent(upEventCaptor.capture());
  verifyNoMoreInteractions(eventDispatcher);

  upEventCaptor.getValue().dispatch(eventEmitterModuleMock);
  verify(eventEmitterModuleMock).receiveTouches(
      eq("topTouchEnd"),
      upActionTouchesArgCaptor.capture(),
      any(WritableArray.class));
  verifyNoMoreInteractions(eventEmitterModuleMock);

  assertThat(upActionTouchesArgCaptor.getValue().size()).isEqualTo(1);
  assertThat(upActionTouchesArgCaptor.getValue().getMap(0)).isEqualTo(
      JavaOnlyMap.of(
          "pageX",
          0.,
          "pageY",
          0.,
          "locationX",
          0.,
          "locationY",
          0.,
          "target",
          rootViewId,
          "timestamp",
          (double) ts,
          "identifier",
          0.));

  // Test other action
  reset(eventDispatcher);
  rootView.onTouchEvent(
      MotionEvent.obtain(50, new Date().getTime(), MotionEvent.ACTION_HOVER_MOVE, 0, 0, 0));
  verifyNoMoreInteractions(eventDispatcher);
}
 
Example #12
Source File: ReactViewPager.java    From react-native-image-zoom with MIT License 4 votes vote down vote up
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    mEventDispatcher.dispatchEvent(
            new PageScrollEvent(getId(), SystemClock.nanoTime(), position, positionOffset));
}