Exploring Android Vibrator API

M Farhan Majid
3 min readAug 22, 2021

Let’s take a look at another old API in Android library: Vibrator. As the name clearly states, Vibrator is a library that allows you to manage device vibration. This library has existed since API level 1 and has received a lot of updates in the most recent version, Android 12 (API level 31).

This article explores what you can do with Vibration API up until API level 30 (Android 11).

Where’s the source code?

tl;dr

There are 3 different types of vibrations that you can use in Vibration API:

  1. Constant Vibration: Vibrate the device for a certain milliseconds.
  2. Pattern Vibration: Vibrate the device according to a pattern. This pattern dictates how long device should turn on and off the vibrator. For example, turn off for 500ms, and then turn on for 1000ms, and then turn off for 500ms. You can repeat this pattern vibration indefinitely.
  3. Effect Vibration: This is the more modern way of managing device vibration (requires API level 26 at the very minimum). There are 4 types of effect vibrations:
    a. One shot Vibration: Similar to constant vibration, but you can determine the vibration amplitude (the strength of vibration).
    b. Predefined Vibration: Vibrate the device according to Android’s predefined vibration patterns. The available patterns are Tick, Click, Double Click, and Heavy Click.
    c. Waveform Vibration: Similar to pattern vibration, but you can determine the vibration amplitudes.
    d. Composition Vibration: Similar to pattern vibration, but you can only compose the pattern from the Android’s predefined vibration primitives. The available primitives are Tick, Click, Quick Fall, Quick Rise, and Slow Rise.

There’s also something AudioAttributes that you can pass as a parameter for the vibrating methods. Basically, what this does is giving some metadata what the vibration is used for (e.g., notification or alarm).

If you run the source code from this article, you can test every vibration types on your own device:

Test every type of vibration with this application

Step by Step Explanation

Now, I will explain how you can start using Vibrator API in your application. I won’t cover every type of vibrations explained in the previous section but only the most basic type of vibration, which is Constant Vibration. Please refer to the source code provided above for more information about the other types of vibration.

Let’s start making the app!

1. Open Android Studio. Create new project with “Empty Activity” option.

2. Add android.permission.VIBRATE to your AndroidManifest.xml like this:

3. Get the Vibrator service in your MainActivity.kt like this:

4. Call vibrate() method from the Vibrator service on onCreate method like this:

5. And that’s it! Now, when you run the application for the first time, your device will vibrate for 2 seconds.

Thanks for reading!

--

--

No responses yet