조현욱 조현욱 - 2 months ago 9
Android Question

How can I every 1 second command intentfilter on android?

I want every 1 second registerReceiver.

I try

registerReceiver(receiver, new IntentFilter(Intent.ACTION_TIME_TICK));


but this code every 1 minute

I want every 1 second.

Perhaps, android have a form ?

thanks

Answer

What are you trying to accomplish? If you just want to have some code executed every 1s, don't user a BroadcastReceiver. Receivers result in inter-process communication every time they are triggered which is (relatively) expensive.

Best way would be to use a handler,

private static final long TICK_INTERVAL = TimeUnit.SECONDS.toMillis(1);
private static final Handler tickHandler = new Handler(Looper.getMainLooper());

public void onResume() {
  super.onResume();
  tick(TICK_INTERVAL);
}

private void tick(final long interval) {
  tickHandler.postDelayed(
    new Runnable() {
      public void run() {
        tick(interval);
        onTick();
      }
    },
  );
}

protected void onTick() {
  // do something
}

Ensure you stop the ticking when your activity pauses,

public void onPause() {
  super.onPause();
  tickHandler.removeCallbacksAndMessages(null);
}