Skip to content

Commit 012ff83

Browse files
l-jonasfornwall
authored andcommitted
Add limit for the bell (vibration)
This fixes #442
1 parent a082c63 commit 012ff83

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
}

app/src/main/java/com/termux/app/TermuxActivity.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ public void onBell(TerminalSession session) {
400400
mBellSoundPool.play(mBellSoundId, 1.f, 1.f, 1, 0, 1.f);
401401
break;
402402
case TermuxPreferences.BELL_VIBRATE:
403-
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(50);
403+
BellUtil.with(TermuxActivity.this).doBell();
404404
break;
405405
case TermuxPreferences.BELL_IGNORE:
406406
// Ignore the bell character.

0 commit comments

Comments
 (0)