Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: [Android] Optimize condition logic #114

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,33 +18,33 @@ public class RNReactNativeHapticFeedbackModuleImpl {

public static final String NAME = "RNHapticFeedback";

public static boolean isVibrationEnabled(Context context) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

private static boolean isVibrationEnabled(Context context, Vibrator vibrator) {
// 1. Check the vibration function of the user's device
boolean hasVibrator = vibrator != null && vibrator.hasVibrator();
if (!vibrator.hasVibrator()) return false;

AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager == null) return false;

// 2. Check if the user has turned on the sound
boolean isVolumeOn = audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT;
if (isVolumeOn) return true;

// 3. Check if the user has set the vibrate mode
boolean isVibrateMode = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;

return hasVibrator && (isVolumeOn || isVibrateMode);
return isVibrateMode;
}

public static void trigger(ReactApplicationContext reactContext, String type, ReadableMap options) {
Vibrator vibrator = (Vibrator) reactContext.getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator == null) return;

// Check system settings, if disabled and we're not explicitly ignoring then return immediatly
boolean ignoreAndroidSystemSettings = options.getBoolean("ignoreAndroidSystemSettings");
boolean isVibrationEnabled = isVibrationEnabled(reactContext);
if (ignoreAndroidSystemSettings == false && !isVibrationEnabled(reactContext, vibrator)) return;

if (ignoreAndroidSystemSettings == false && !isVibrationEnabled) return;
Vibrator v = (Vibrator) reactContext.getSystemService(Context.VIBRATOR_SERVICE);
Vibrate targetVibration = VibrateFactory.getVibration(type);
if (targetVibration == null) return;

if (v == null || targetVibration == null) return;

targetVibration.apply(v);
targetVibration.apply(vibrator);
}
}