540

I wrote an Android application. Now, I want to make the device vibrate when a certain action occurs. How can I do this?

Yogesh Umesh Vaity
  • 16,749
  • 10
  • 82
  • 69
Billie
  • 8,100
  • 12
  • 31
  • 62

13 Answers13

1058

Try:

import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
    //deprecated in API 26 
    v.vibrate(500);
}

Note:

Don't forget to include permission in AndroidManifest.xml file:

<uses-permission android:name="android.permission.VIBRATE"/>
vallentin
  • 19,107
  • 6
  • 43
  • 68
Paresh Mayani
  • 122,920
  • 69
  • 234
  • 290
  • 3
    Is there a way to cancel the vibration of all the phone? thanks! – Javi Mar 09 '14 at 14:35
  • 14
    @joshsvoss It's 500 milliseconds which is just half a second. Check out google docs. http://developer.android.com/reference/android/os/Vibrator.html – cjayem13 Sep 23 '14 at 13:08
  • 6
    it gives me: context cannot be resolved or is not a field .. ?! what is the problem – McLan Oct 09 '14 at 15:58
  • 3
    vibrate is now deprecated. Use the solution by Hitesh Sahu instead. – Ray Li Sep 08 '17 at 17:32
  • 2
    This method was deprecated in API level 26. Use `vibrate(VibrationEffect)` instead. – Timo Bähr Jan 23 '18 at 15:05
  • 1
    Use Vibrator v=(Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(50); if you are doing it from dialog. – user55924 Mar 09 '18 at 07:06
  • 1
    I've tried your code and it works perfectly. But if "Battery saver" is on and the device is not connected to a power supply ("charging"), nothing happens. I guess this is a "feature" that prevents power consumption. – Gyro Gearloose Jan 02 '21 at 17:21
671

Grant Vibration Permission

Before you start implementing any vibration code, you have to give your application the permission to vibrate:

<uses-permission android:name="android.permission.VIBRATE"/>

Make sure to include this line in your AndroidManifest.xml file.

Import the Vibration Library

Most IDEs will do this for you, but here is the import statement if yours doesn't:

 import android.os.Vibrator;

Make sure this in the activity where you want the vibration to occur.

How to Vibrate for a Given Time

In most circumstances, you'll be wanting to vibrate the device for a short, predetermined amount of time. You can achieve this by using the vibrate(long milliseconds) method. Here is a quick example:

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 400 milliseconds
v.vibrate(400);

That's it, simple!

How to Vibrate Indefinitely

It may be the case that you want the device to continue vibrating indefinitely. For this, we use the vibrate(long[] pattern, int repeat) method:

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};

// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, 0);

When you're ready to stop the vibration, just call the cancel() method:

v.cancel();

How to use Vibration Patterns

If you want a more bespoke vibration, you can attempt to create your own vibration patterns:

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Start without a delay
// Each element then alternates between vibrate, sleep, vibrate, sleep...
long[] pattern = {0, 100, 1000, 300, 200, 100, 500, 200, 100};

// The '-1' here means to vibrate once, as '-1' is out of bounds in the pattern array
v.vibrate(pattern, -1);

More Complex Vibrations

There are multiple SDKs that offer a more comprehensive range of haptic feedback. One that I use for special effects is Immersion's Haptic Development Platform for Android.

Troubleshooting

If your device won't vibrate, first make sure that it can vibrate:

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Output yes if can vibrate, no otherwise
if (v.hasVibrator()) {
    Log.v("Can Vibrate", "YES");
} else {
    Log.v("Can Vibrate", "NO");
}

Secondly, please ensure that you've given your application the permission to vibrate! Refer back to the first point.

Liam George Betsworth
  • 17,558
  • 5
  • 37
  • 42
  • 29
    Excellent answer, although I would be wary of playing a vibration indefinitely. Please be responsible when using this feature! – Dave Jul 17 '13 at 18:04
  • 4
    Great answer, but one thing. When you say 'The '0' here means to repeat indefinitely', although true, is a bit misleading. This number is the Index of the pattern array that the pattern will start at when repeating. – aaronvargas Oct 02 '14 at 00:23
  • 1
    @aaronvargas Fair point, though that's out of the scope of what most people are trying to achieve. I went for a simple explanation :) – Liam George Betsworth Oct 03 '14 at 10:43
  • @Liam George Betsworth How do I vibrate even the mobile is in silent mode? please. – Parthi Jun 17 '15 at 06:46
  • @Dave as I have to forcibly close my app :) – Muhammad Saqib Aug 24 '15 at 19:56
  • It does repeat the pattern forever, but how about vibrating for 3 times only for example (i.e.: start + vibrate + sleep + vibrate + sleep + vibrate + stop) ?!! – McLan Dec 13 '16 at 13:15
  • @Suda.nese Read the section on 'how to use vibration patterns'. Something like: `long[] pattern = {0, 100, 100, 100, 100, 100}; v.vibrate(pattern, -1);` – Liam George Betsworth Dec 15 '16 at 10:35
  • 1
    The immersion-link is down and I can't find it on archive.org :( – looper Apr 21 '17 at 07:17
  • And it switches between SLEEP and THEN VIBRATE. Not the other way around. – Filip Petrovic Jul 10 '17 at 17:22
  • @FilipPetrovic That is mentioned in the code comments. I think you missed the 'start without delay' comment on the line above. Apologies if this is confusing. – Liam George Betsworth Jul 11 '17 at 14:48
  • Don't forget to uninstall the app if you are creating a `NotificationChannel` for `Notfication`. Otherwise the pattern does not override the previous vibration patterns. – ArtiomLK Jan 25 '18 at 02:58
  • @LiamGeorgeBetsworth - Is there any way to get vibration continuously without any delay or somewhere delay but in a random manner rather than a specific (as you described above as vibrate, delay, vibrate, delay ... )? – Irfan Akram Apr 07 '20 at 20:44
88

Update 2017 vibrate(interval) method is deprecated with Android-O(API 8.0)

To support all Android versions use this method.

// Vibrate for 150 milliseconds
private void shakeItBaby() {
    if (Build.VERSION.SDK_INT >= 26) {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
    } else {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);
    }
}

Kotlin:

// Vibrate for 150 milliseconds
private fun shakeItBaby(context: Context) {
    if (Build.VERSION.SDK_INT >= 26) {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE))
    } else {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(150)
    }
}
Hitesh Sahu
  • 31,496
  • 11
  • 150
  • 116
  • 2
    We don't need runtime permission for Vibration. Vibration is not a dangerous permission, so it has to be only declared in the manifest. [https://developer.android.com/guide/topics/permissions/normal-permissions.html](Source) – Roon13 Sep 18 '17 at 17:34
  • @BugsHappen documentation moved. Will update it or delete it. – Roon13 May 15 '18 at 20:07
  • The only thing that I would add is that if you are using this in an Activity and don't have a specific Context variable, then replace `getSystemService` with `this.getContext().getSystemService` – DrMcCleod Oct 29 '18 at 13:40
  • 5
    you sir earned an upvote 'cause of that functions name, touché – Starwave Jan 26 '19 at 13:28
24

Above answers are perfect. However I wanted to vibrate my app exactly twice on button click and this small information is missing here, hence posting for future readers like me. :)

We have to follow as mentioned above and the only change will be in the vibrate pattern as below,

long[] pattern = {0, 100, 1000, 300};
v.vibrate(pattern, -1); //-1 is important

This will exactly vibrate twice. As we already know

  1. 0 is for delay
  2. 100 says vibrate for 100ms for the first time
  3. next comes delay of 1000ms
  4. and post that vibrate again for 300ms

One can go on and on mentioning delay and vibration alternatively (e.g. 0, 100, 1000, 300, 1000, 300 for 3 vibrations and so on..) but remember @Dave's word use it responsibly. :)

Also note here that the repeat parameter is set to -1 which means the vibration will happen exactly as mentioned in the pattern. :)

lue
  • 399
  • 4
  • 16
Atul O Holic
  • 6,216
  • 4
  • 36
  • 72
  • Why does -1 mean the vibration will happen exactly as mentioned in the pattern? Thanks! – Ruchir Baronia Nov 08 '15 at 19:02
  • @Rich Please refer to my answer. The '-1' is the index at which the vibration will try to repeat from, after following the pattern for the first time. '-1' is out of bounds, therefore the vibration does not repeat. – Liam George Betsworth Nov 09 '15 at 11:43
  • @Rich - Liam George Betsworth is correct. Android docs say - To cause the pattern to repeat, pass the index into the pattern array at which to start the repeat, or -1 to disable repeating. Link - http://developer.android.com/reference/android/os/Vibrator.html#vibrate(long[], int) – Atul O Holic Nov 10 '15 at 08:44
21

Vibrate without using permission

If you want to simply vibrate the device once to provide a feedback on a user action. You can use performHapticFeedback() function of a View. This doesn't need the VIBRATE permission to be declared in the manifest.

Use the following function as a top level function in some common class like Utils.kt of your project:

/**
 * Vibrates the device. Used for providing feedback when the user performs an action.
 */
fun vibrate(view: View) {
    view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}

And then use it anywhere in your Fragment or Activity as following:

vibrate(requireView())

Simple as that!

Yogesh Umesh Vaity
  • 16,749
  • 10
  • 82
  • 69
14

I struggled understanding how to do this on my first implementation - make sure you have the following:

1) Your device supports vibration (my Samsung tablet did not work so I kept re-checking the code - the original code worked perfectly on my CM Touchpad

2) You have declared above the application level in your AndroidManifest.xml file to give the code permission to run.

3) Have imported both of the following in to your MainActivity.java with the other imports: import android.content.Context; import android.os.Vibrator;

4) Call your vibration (discussed extensively in this thread already) - I did it in a separate function and call this in the code at other points - depending on what you want to use to call the vibration you may need an image (Android: long click on a button -> perform actions) or button listener, or a clickable object as defined in XML (Clickable image - android):

 public void vibrate(int duration)
 {
    Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibs.vibrate(duration);    
 }
Community
  • 1
  • 1
mklopfer
  • 341
  • 3
  • 4
10

Kotlin update for more type safety

Use it as a top level function in some common class of your project such as Utils.kt

// Vibrates the device for 100 milliseconds.
fun vibrateDevice(context: Context) {
    val vibrator = getSystemService(context, Vibrator::class.java)
    vibrator?.let {
        if (Build.VERSION.SDK_INT >= 26) {
            it.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            @Suppress("DEPRECATION")
            it.vibrate(100)
        }
    }
}

And then call it anywhere in your code as following:

vibrateDevice(requireContext())

Explanation

Using Vibrator::class.java is more type safe than using String constants.

We check the vibrator for nullability using let { }, because if the vibration is not available for the device, the vibrator will be null.

It's ok to supress deprecation in else clause, because the warning is from newer SDK.

We don't need to ask for permission at runtime for using vibration. But we need to declare it in AndroidManifest.xml as following:

<uses-permission android:name="android.permission.VIBRATE"/>
Yogesh Umesh Vaity
  • 16,749
  • 10
  • 82
  • 69
6

Vibrating in Patterns/Waves:

import android.os.Vibrator;
...
// Pause for 500ms, vibrate for 500ms, then start again
private static final long[] VIBRATE_PATTERN = { 500, 500 };

mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // API 26 and above
    mVibrator.vibrate(VibrationEffect.createWaveform(VIBRATE_PATTERN, 0));
} else {
    // Below API 26
    mVibrator.vibrate(VIBRATE_PATTERN, 0);
}

Plus

The necessary permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.VIBRATE"/>
Maksim Ivanov
  • 2,581
  • 23
  • 21
5
<uses-permission android:name="android.permission.VIBRATE"/>

should be added inside <manifest> tag and outside <application> tag.

Sivagami Nambi
  • 324
  • 4
  • 9
4

Above answer is very correct but I'm giving an easy step to do it:

 private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000,  1000, 1000, 1000 };

  public void longVibrate(View v) 
  {
     vibrateMulti(THREE_CYCLES);
  }

  private void vibrateMulti(long[] cycles) {
      NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
      Notification notification = new Notification();

      notification.vibrate = cycles; 
      notificationManager.notify(0, notification);
  }

And then in your xml file:

<button android:layout_height="wrap_content" 
        android:layout_width ="wrap_content" 
        android:onclick      ="longVibrate" 
        android:text         ="VibrateThrice">
</button>

That's the easiest way.

Alex Meuer
  • 935
  • 18
  • 33
dondondon
  • 743
  • 6
  • 4
4

I use the following utils method:

public static final void vibratePhone(Context context, short vibrateMilliSeconds) {
    Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(vibrateMilliSeconds);
}

Add the following permission to the AndroidManifest file

<uses-permission android:name="android.permission.VIBRATE"/>

You can use overloaded methods in case if you wish to use different types of vibrations (patterns / indefinite) as suggested above.

Mahendra Liya
  • 11,166
  • 10
  • 79
  • 105
2

Use this:

import android.os.Vibrator;
     ...
     Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
     // Vibrate for 1000 milliseconds
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            v.vibrate(VibrationEffect.createOneShot(1000,VibrationEffect.DEFAULT_AMPLITUDE));
     }else{
     //deprecated in API 26 
            v.vibrate(1000);
     }

Note:

Don't forget to include permission in AndroidManifest.xml file:

<uses-permission android:name="android.permission.VIBRATE"/>
1

You can Vibrate the Device and its work

   Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
           v.vibrate(100);

Permission is necessary but not on runtime permission required

<uses-permission android:name="android.permission.VIBRATE"/>
Ahmad
  • 244
  • 2
  • 12