Added a small vibration when the phone is shaken to reset the sleep timer (#7714)

This commit is contained in:
eblis 2025-04-05 17:04:26 +03:00 committed by GitHub
parent f18b09fbf5
commit 699b96b174
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -5,6 +5,10 @@ import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.VibratorManager;
import android.util.Log;
public class ShakeListener implements SensorEventListener {
@ -42,16 +46,37 @@ public class ShakeListener implements SensorEventListener {
}
}
protected void vibrate() {
final Vibrator vibrator;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
VibratorManager vibratorManager = (VibratorManager)
mContext.getSystemService(Context.VIBRATOR_MANAGER_SERVICE);
vibrator = vibratorManager.getDefaultVibrator();
} else {
vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
}
final int duration = 100;
if (vibrator != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(duration, 120));
} else {
vibrator.vibrate(duration);
}
}
}
@Override
public void onSensorChanged(SensorEvent event) {
float gX = event.values[0] / SensorManager.GRAVITY_EARTH;
float gY = event.values[1] / SensorManager.GRAVITY_EARTH;
float gZ = event.values[2] / SensorManager.GRAVITY_EARTH;
double gForce = Math.sqrt(gX*gX + gY*gY + gZ*gZ);
double gForce = Math.sqrt(gX * gX + gY * gY + gZ * gZ);
if (gForce > 2.25) {
Log.d(TAG, "Detected shake " + gForce);
mSleepTimer.restart();
vibrate();
}
}