|
| 1 | +package com.termux.app; |
| 2 | + |
| 3 | +import android.content.Context; |
| 4 | +import android.os.Handler; |
| 5 | +import android.os.Looper; |
| 6 | +import android.os.SystemClock; |
| 7 | +import android.os.Vibrator; |
| 8 | + |
| 9 | +public class BellUtil { |
| 10 | + private static BellUtil instance = null; |
| 11 | + private static final Object lock = new Object(); |
| 12 | + |
| 13 | + public static BellUtil with(Context context) { |
| 14 | + if (instance == null) { |
| 15 | + synchronized (lock) { |
| 16 | + if (instance == null) { |
| 17 | + instance = new BellUtil((Vibrator) context.getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE)); |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + return instance; |
| 23 | + } |
| 24 | + |
| 25 | + private static final long DURATION = 50; |
| 26 | + private static final long MIN_PAUSE = 3 * DURATION; |
| 27 | + |
| 28 | + private final Handler handler = new Handler(Looper.getMainLooper()); |
| 29 | + private long lastBell = 0; |
| 30 | + private final Runnable bellRunnable; |
| 31 | + |
| 32 | + private BellUtil(final Vibrator vibrator) { |
| 33 | + bellRunnable = new Runnable() { |
| 34 | + @Override |
| 35 | + public void run() { |
| 36 | + if (vibrator != null) { |
| 37 | + vibrator.vibrate(DURATION); |
| 38 | + } |
| 39 | + } |
| 40 | + }; |
| 41 | + } |
| 42 | + |
| 43 | + public synchronized void doBell() { |
| 44 | + long now = now(); |
| 45 | + long timeSinceLastBell = now - lastBell; |
| 46 | + |
| 47 | + if (timeSinceLastBell < 0) { |
| 48 | + // there is a next bell pending; don't schedule another one |
| 49 | + } else if (timeSinceLastBell < MIN_PAUSE) { |
| 50 | + // there was a bell recently, scheudle the next one |
| 51 | + handler.postDelayed(bellRunnable, MIN_PAUSE - timeSinceLastBell); |
| 52 | + lastBell = lastBell + MIN_PAUSE; |
| 53 | + } else { |
| 54 | + // the last bell was long ago, do it now |
| 55 | + bellRunnable.run(); |
| 56 | + lastBell = now; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + private long now() { |
| 61 | + return SystemClock.uptimeMillis(); |
| 62 | + } |
| 63 | +} |
0 commit comments