Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @SuppressWarnings({"MissingPermission"})
- public static void DoHapticFeedback(Activity activity, Context ctx, int strength, boolean ignoreDeviceHapticSetting) {
- if(ctx == null || activity == null || activity.isFinishing() || activity.isDestroyed()) return;
- View rootView = null;
- try {
- Window activityWindow = activity.getWindow();
- if (activityWindow != null) {
- View activityView = activityWindow.getDecorView();
- if(activityView != null) {
- rootView = activityView.findViewById(android.R.id.content);
- } else {
- Log.e("PicklePKG", "Vibration.DoHapticFeedback(..) null activityView!");
- return;
- }
- } else {
- Log.e("PicklePKG", "Vibration.DoHapticFeedback(..) null activityWindow!");
- return;
- }
- } catch (Exception e) {
- Log.e("PicklePKG", "Vibration.DoHapticFeedback(..) failed to get rootView - " + e);
- return;
- }
- if (rootView == null) {
- Log.e("PicklePKG", "Vibration.DoHapticFeedback(..) rootView was null!");
- return;
- }
- // If haptic feedback isn't already enabled, enable it now
- if (!rootView.isHapticFeedbackEnabled())
- rootView.setHapticFeedbackEnabled(true);
- int type = HapticFeedbackConstants.CLOCK_TICK;
- switch(strength){
- /*case 1: type = HapticFeedbackConstants.VIRTUAL_KEY; break;*/
- case 2: type = HapticFeedbackConstants.KEYBOARD_TAP; break;
- case 3: type = HapticFeedbackConstants.VIRTUAL_KEY; break;
- case 4: type = HapticFeedbackConstants.LONG_PRESS; break;
- }
- if(ignoreDeviceHapticSetting) {
- // Android API 33+ does not support the flag to ignore device haptic settings, if we already have the VIBRATE permission just use the vibrator for haptics
- if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
- if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.VIBRATE) == PackageManager.PERMISSION_GRANTED) {
- long vibrationMilliseconds = 1L;
- // Convert strength to millisecond durations
- switch (strength) {
- /*case 1: vibrationMilliseconds = 1L; break;*/
- case 2: vibrationMilliseconds = 20L; break;
- case 3: vibrationMilliseconds = 50L; break;
- case 4: vibrationMilliseconds = 100L; break;
- }
- DoVibrate(ctx, vibrationMilliseconds, 1);
- } else {
- rootView.performHapticFeedback(type);
- }
- } else {
- rootView.performHapticFeedback(type, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
- }
- } else {
- rootView.performHapticFeedback(type);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment