Search code examples
androidflutterandroid-vibrationvibrationhaptic-feedback

Flutter: vibrate on device for non-standard length of time


I am trying to build a Flutter application for Android that vibrates the phone both

  • for sufficiently long and sufficiently forcefully that even when the user's phone is in their pocket, the vibration is noticeable
  • in a specific pattern which the user can identify (like Morse code)

I have found ways of producing haptic feedback, such as HapticFeedback.vibrate, HapticFeedback.lightImpact; however, none of these allow me to control the length of the vibration.

Is there any way in which I can make the phone vibrate for a specified length of time (e.g. 250ms)?


Solution

  • I'm answering my own question as I've found a solution that works well for Android; using the plugin vibrate, the following code works perfectly well to send custom lengths of vibration and patterns of vibration:

    class GoodVibrations {
      static const MethodChannel _channel = const MethodChannel(
          'github.com/clovisnicolas/flutter_vibrate');
    
      ///Vibrate for ms milliseconds
      static Future vibrate(ms) =>
          _channel.invokeMethod("vibrate", {"duration": ms});
    
      ///Take in an Iterable<int> of the form
      ///[l_1, p_1, l_2, p_2, ..., l_n]
      ///then vibrate for l_1 ms,
      ///pause for p_1 ms,
      ///vibrate for l_2 ms,
      ///...
      ///and vibrate for l_n ms.
      static Future vibrateWithPauses(Iterable<int> periods) async {
        bool isVibration = true;
        for (int d in periods) {
          if (isVibration && d > 0) {
            vibrate(d);
          }
          await new Future.delayed(Duration(milliseconds: d));
          isVibration = !isVibration;
        }
      }
    }