public void run() {
   long base = mBase;
   long now = SystemClock.uptimeMillis();
   long diff = now - base;
   int duration = mDuration;
   float val = diff / (float) duration;
   if (!mDirection) {
     val = 1.0f - val;
   }
   if (val > 1.0f) {
     val = 1.0f;
   } else if (val < 0.0f) {
     val = 0.0f;
   }
   float old = mValue;
   mValue = val;
   mCallback.onTweenValueChanged(val, old);
   int frame = (int) (diff / FRAME_TIME);
   long next = base + ((frame + 1) * FRAME_TIME);
   if (diff < duration) {
     mHandler.postAtTime(this, next);
   }
   if (diff >= duration) {
     mCallback.onTweenFinished();
     mRunning = false;
   }
 }
  @Test
  public void shouldRemoveTaggedCallback() throws Exception {
    ShadowLooper.pauseMainLooper();
    Handler handler = new Handler();

    final int[] count = new int[1];
    Runnable r =
        new Runnable() {
          @Override
          public void run() {
            count[0]++;
          }
        };

    String tag1 = "tag1", tag2 = "tag2";

    handler.postAtTime(r, tag1, 100);
    handler.postAtTime(r, tag2, 105);

    handler.removeCallbacks(r, tag2);
    ShadowLooper.unPauseMainLooper();

    assertThat(count[0]).as("run count").isEqualTo(1);
    // This assertion proves that it was the first runnable that ran,
    // which proves that the correctly tagged runnable was removed.
    assertThat(shadowOf(handler.getLooper()).getScheduler().getCurrentTime())
        .as("currentTime")
        .isEqualTo(100);
  }
        @Override
        public void run() {
          long now = SystemClock.uptimeMillis();
          long millis = mTerminationTimeInMillis - now;
          long halfOfMillis = mTerminationTimeInMillis - (mTimerDelayInMillis / 2) - now;

          if (millis <= 0) {
            cancelTimer();

            try {
              this.finalize();
            } catch (Throwable e) {
              e.printStackTrace();
            }
            return;
          }

          if (mIsMrXTimer) {
            mTextViewTimerBig.setText("Time left: " + generateText(millis));
            mTextViewTimerSmall.setText(mTextAgetns + generateText(halfOfMillis));
          } else {
            mTextViewTimerBig.setText("Time left: " + generateText(halfOfMillis));
            mTextViewTimerSmall.setText(mTextMrX + generateText(millis));
          }

          mHandler.postAtTime(this, now + 1000);
        }
Exemple #4
0
 /**
  * 执行逻辑过程中仅保留一次执行
  *
  * @param r
  * @return
  */
 public static boolean postOnce(Runnable r) {
   if (uiHandler == null) {
     return false;
   }
   uiHandler.removeCallbacks(r, token);
   return uiHandler.postAtTime(r, token, SystemClock.uptimeMillis());
 }
 @Override
 public void run() {
   if (downView == null) {
     return;
   }
   handler.removeCallbacksAndMessages(downView);
   handler.postAtTime(this, downView, SystemClock.uptimeMillis() + normalInterval);
   clickListener.onClick(downView);
 }
  public void doNJStuff() {
    if (handler != null) {
      handler.removeCallbacks(runnable);
    }
    handler = null;
    try {
      String webid = mURL;
      String pubToken;
      pubToken = njt(webid);
      thisURL =
          "http://pub2.camera.trafficland.com/image/live.jpg?system=njtp&webid="
              + webid
              + "&pubtoken="
              + pubToken
              + "&r="
              + Math.random();
      Log.d("THISURL", thisURL);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    image = ImageOperations(getActivity().getApplicationContext(), thisURL, "image.jpg");
    if (image != null) {
      imageView.setImageDrawable(image);

      Toast.makeText(
              getActivity().getApplicationContext(),
              "Camera refreshes every " + String.valueOf(delay / 1000) + " seconds",
              Toast.LENGTH_LONG)
          .show();
      handler = new Handler();
      runnable =
          new Runnable() {
            public void run() {
              trimCache(getActivity());
              image = ImageOperations(getActivity().getApplicationContext(), thisURL, "image.jpg");
              imageView.setImageDrawable(image);
              handler.postDelayed(this, delay);
            }
          };
      handler.postAtTime(runnable, 4500);
    } else {
      final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
      alertDialog.setTitle("Bad Camera");
      alertDialog.setMessage("This camera is disabled, please select another one");
      alertDialog.setButton(
          "Cancel",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              getSupportActivity().getSupportFragmentManager().popBackStack();
              return;
            }
          });
      alertDialog.show();
    }
  }
  /**
   * Set an alarm time. Any previously set alarm will be discarded, that means only one alarm can be
   * set at a time.
   *
   * @param alarm The time in milliseconds since the epoch when to trigger the alarm.
   */
  public void setNextAlarm(long alarm) {
    if (mHandler == null) {
      mHandler = new Handler();
    }

    // set new callback at the specified alarm
    mHandler.removeCallbacks(mNotifier);
    mHandler.postAtTime(
        mNotifier, alarm - System.currentTimeMillis() + android.os.SystemClock.uptimeMillis());
  }
        public void run() {
          if (mAdapter != null) {
            // This is used to refresh session title colors.
            mAdapter.notifyDataSetChanged();
          }

          // Check again on the next quarter hour, with some padding to
          // account for network
          // time differences.
          long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000;
          mMessageQueueHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour);
        }
        @Override
        public void run() {

          // Execute 1/50th of a second of BBC micro!
          long now = android.os.SystemClock.uptimeMillis();
          handler.postAtTime(runInt50, now + 20);
          if (beebView.gl == null) {
            if (beebView.egl == null) { // no surface yet
              return;
            }
            beebView.initgl();
            bbcInitGl(beebView.width, beebView.height);
          }
          int trigger = bbcRun();

          // Handle trigger events
          if (controller.controllerInfo != null) {
            final List<TriggerAction> triggers = controller.controllerInfo.triggers;
            if (trigger != last_trigger && triggers != null) {
              Log.d("Trigger!", "PC hit trigger " + trigger);
              last_trigger = trigger;
              if (triggers.size() >= trigger) {
                onTriggerFired(controller.controllerInfo.triggers.get(trigger - 1));
              }
            }
          }

          // Automatic keyboard text
          if (keyboardTextWait > 0) {
            keyboardTextWait--;
          } else {
            if (keyboardTextEvents.size() > 0) {
              final KeyEvent event = keyboardTextEvents.remove(0);
              if (event.getAction() == KeyEvent.ACTION_DOWN) {
                onKeyDown(event.getKeyCode(), event);
              }
              if (event.getAction() == KeyEvent.ACTION_UP) {
                handler.postDelayed(
                    new Runnable() {
                      @Override
                      public void run() {
                        onKeyUp(event.getKeyCode(), event);
                        keyboardTextWait = 1;
                      }
                    },
                    10);
              }
            }
          }
        }
Exemple #10
0
        public void run() {

          // update time
          long elapsedTime = System.currentTimeMillis() - mTimerStart;

          // schedule event for next second
          mTimeHandler.postAtTime(this, SystemClock.uptimeMillis() + SECOND);

          // inform listener about the time changed
          if (mListener != null) {
            mListener.onTimerTick();

            if (mIsCountdownEnabled && elapsedTime >= mCountdown) {
              mListener.onCountdownFinish();
            }
          }
        }
 /**
  * Starts the tweening.
  *
  * @param direction If direction is true, the value goes towards 1.0f. If direction is false, the
  *     value goes towards 0.0f.
  * @param baseTime The time to use as zero for this animation, in the {@link
  *     SystemClock.uptimeMillis} time base. This allows you to synchronize multiple animations.
  */
 public void start(boolean direction, long baseTime) {
   if (direction != mDirection) {
     if (!mRunning) {
       mBase = baseTime;
       mRunning = true;
       mCallback.onTweenStarted();
       long next = SystemClock.uptimeMillis() + FRAME_TIME;
       mHandler.postAtTime(mTick, next);
     } else {
       // reverse direction
       long now = SystemClock.uptimeMillis();
       long diff = now - mBase;
       mBase = now + diff - mDuration;
     }
     mDirection = direction;
   }
 }
  @Override
  public void onChange(final boolean selfChange) {
    if (mOnChangeTask == null) {
      mOnChangeTask =
          new Runnable() {
            @Override
            public void run() {
              onChangeThrottled();
              mOnChangeTask = null;
            }
          };

      long now = SystemClock.uptimeMillis();
      mHandler.postAtTime(mOnChangeTask, now + mUpdateThrottle);
    }
    super.onChange(selfChange);
  }
  public void appTransitionStarting(long startTime, long duration) {
    if (mTransitionPending && mTintChangePending) {
      mTintChangePending = false;
      animateIconTint(
          mPendingDarkIntensity, Math.max(0, startTime - SystemClock.uptimeMillis()), duration);

    } else if (mTransitionPending) {

      // If we don't have a pending tint change yet, the change might come in the future until
      // startTime is reached.
      mTransitionDeferring = true;
      mTransitionDeferringStartTime = startTime;
      mTransitionDeferringDuration = duration;
      mHandler.removeCallbacks(mTransitionDeferringDoneRunnable);
      mHandler.postAtTime(mTransitionDeferringDoneRunnable, startTime);
    }
    mTransitionPending = false;
  }
 public boolean onTouch(View view, MotionEvent motionEvent) {
   switch (motionEvent.getAction()) {
     case MotionEvent.ACTION_DOWN:
       downView = view;
       handler.removeCallbacks(handlerRunnable);
       handler.postAtTime(
           handlerRunnable, downView, SystemClock.uptimeMillis() + initialInterval);
       clickListener.onClick(view);
       return true;
     case MotionEvent.ACTION_UP:
     case MotionEvent.ACTION_CANCEL:
     case MotionEvent.ACTION_OUTSIDE:
       handler.removeCallbacksAndMessages(downView);
       downView = null;
       return true;
   }
   return false;
 }
  @Override
  protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
    final boolean isAnimationPlayed = super.awakenScrollBars(startDelay, invalidate);

    if (isAnimationPlayed == true && scrollBarPanel != null) {
      if (scrollBarPanel.getVisibility() == View.GONE) {
        scrollBarPanel.setVisibility(View.VISIBLE);
        if (inAnimation != null) {
          scrollBarPanel.startAnimation(inAnimation);
        }
      }

      handler.removeCallbacks(scrollBarPanelFadeRunnable);
      handler.postAtTime(
          scrollBarPanelFadeRunnable, AnimationUtils.currentAnimationTimeMillis() + startDelay);
    }

    return isAnimationPlayed;
  }
Exemple #16
0
        public void run() {
          System.out.println("volup pressed");
          ir.release();

          String coolcmd = "Vol+";
          // Log.i("repeatBtn", "repeat click");

          try {

            sendCommand(coolcmd);
            // Log.i("repeatBtn", "MotionEvent.ACTION_DOWN");
            // mHandler.removeCallbacks(mUpdateTask);

          } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          mHandler.postAtTime(this, SystemClock.uptimeMillis() + 250);
        }
    @Override
    protected Void doInBackground(MediaRecorder... params) {

      /*开始录音*/
      MediaRecorder tmpMediaRecorder = params[0];
      tmpMediaRecorder.start();
      tmpMediaRecorder.setOnInfoListener(
          new OnInfoListener() {
            @Override
            public void onInfo(MediaRecorder mr, int what, int extra) {
              // TODO Auto-generated method stub
              if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
                isMonitorRun = false;
              }
            }
          });

      /*开始监控*/
      isMonitorRun = true;
      while (isMonitorRun) {
        int sVolumeValue = tmpMediaRecorder.getMaxAmplitude();
        if (sVolumeValue > 0) {
          mVolumeSize = 1000 * sVolumeValue / 32768;
          mHandler.postAtTime(
              new Runnable() {
                @Override
                public void run() {
                  // TODO Auto-generated method stub
                  mViewVolume.setText(mVolumeSize + "");
                }
              },
              500);
        }
      }

      /*停止录音*/
      tmpMediaRecorder.stop();
      tmpMediaRecorder.release();
      tmpMediaRecorder = null;
      mCountDownTimer.cancel(); // 停止计时
      return null;
    }
 public void doPAStuff() {
   if (handler != null) {
     handler.removeCallbacks(runnable);
   }
   handler = null;
   image = ImageOperations(getActivity().getApplicationContext(), mURL, "image.jpg");
   if (image != null) {
     imageView.setImageDrawable(image);
     Toast.makeText(
             getActivity().getApplicationContext(),
             "Camera refreshes every " + String.valueOf(delay / 1000) + " seconds",
             Toast.LENGTH_LONG)
         .show();
     Log.i("HERE5", "HERE5");
     handler = new Handler();
     runnable =
         new Runnable() {
           public void run() {
             Log.i("HERE6", "HERE6");
             trimCache(getActivity());
             Log.i("HERE7", "HERE7");
             image = ImageOperations(getActivity().getApplicationContext(), mURL, "image.jpg");
             imageView.setImageDrawable(image);
             handler.postDelayed(this, delay);
           }
         };
     handler.postAtTime(runnable, 4500);
   } else {
     final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
     alertDialog.setTitle("Bad Camera");
     alertDialog.setMessage("This camera is disabled, please select another one");
     alertDialog.setButton(
         "Cancel",
         new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
             getSupportActivity().getSupportFragmentManager().popBackStack();
             return;
           }
         });
     alertDialog.show();
   }
 }
Exemple #19
0
        @Override
        public void run() {
          long currentMilliseconds = System.currentTimeMillis();
          secondsPassed = (secondsPassed + 0x1);
          timer.postAtTime(this, currentMilliseconds);
          timer.postDelayed(updateTimeElasped, 2000);
          CopyDrawImage(canvasDst);
          if (canvasBuffer != null) {

            canvasBuffer.drawBitmap(bitmapDst, 0.0f, 0.0f, null);
            drawWordLines(canvasBuffer);
          }
          stopTimer();
          try {
            view.invalidate();
            GlobalVariables.getInstance().setMoveCursor(true);
            return;
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
  public MyCustomLocationOverlay(Context context, MapView mapView) {
    super(context, mapView);

    this.mapView = mapView;

    slips = new Drawable[4];
    slips[0] = context.getResources().getDrawable(R.drawable.icon_user);
    slips[1] = context.getResources().getDrawable(R.drawable.icon_user);
    slips[2] = context.getResources().getDrawable(R.drawable.icon_user);
    slips[3] = context.getResources().getDrawable(R.drawable.icon_user);
    overlayAnimationTask =
        new Runnable() {
          public void run() {
            currSlip = (currSlip + 1) % slips.length;
            MyCustomLocationOverlay.this.mapView.invalidate();
            handler.removeCallbacks(overlayAnimationTask);
            handler.postDelayed(overlayAnimationTask, 200);
          }
        };
    handler.removeCallbacks(overlayAnimationTask);
    handler.postAtTime(overlayAnimationTask, 100);
  }
 private void postAtTime(Runnable runnable, long timeInNanos) {
   long timeInMillis = TimeUnit.MILLISECONDS.convert(timeInNanos, TimeUnit.NANOSECONDS);
   timerHandler.postAtTime(runnable, timeInMillis);
 }
 private void startIncomeCallTimer(long time) {
   showIncomingCallWindowTaskHandler.postAtTime(
       showIncomingCallWindowTask, SystemClock.uptimeMillis() + time);
 }
 @Override
 public void scheduleDrawable(Drawable who, Runnable what, long when) {
   if (who != null && what != null) {
     mHandler.postAtTime(what, when);
   }
 }
 @Override
 public void scheduleDrawable(Drawable who, Runnable what, long when) {
   handler.postAtTime(what, when);
 }