1

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)?

2 Answers2

2

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;
    }
  }
}
  • You should accept your own answer. Many people only click on questions with accepted answers when looking up a specific problem. – Daneel Jun 15 '18 at 12:38
0

Here is one plugin that can do the work. https://pub.dartlang.org/packages/vibrate

Example from the package:

// Check if the device can vibrate
bool canVibrate = await Vibrate.canVibrate;

For iOS:

// Vibrate
// Vibration duration is a constant 500ms because 
// it cannot be set to a specific duration on iOS.
Vibrate.vibrate()

for Android

// Vibrate with pauses between each vibration
final Iterable<Duration> pauses = [
    const Duration(milliseconds: 500),
    const Duration(milliseconds: 1000),
    const Duration(milliseconds: 500),
];
// vibrate - sleep 0.5s - vibrate - sleep 1s - vibrate - sleep 0.5s - vibrate
Vibrate.vibrate(pauses);

Note that there is only custom vibration for android

Tree
  • 29,135
  • 24
  • 78
  • 98