Vibrate Device Example for Android Studio

Welcome. In this tutorial you will learn how to make your android app make the device vibrate in Android Studio.

Vibrate Device Example for Android Studio

For making your device vibrate in Android Studio, we will have to use the Vibrator class. The vibrator class deals with the vibrating machine present in your device and will make it vibrate for the given duration after which it will stop.

Creating a Vibrator in Android App

First you will have to declare a vibrator object of class Vibrator as shown below:-

Then on the place when you want your device to vibrate,like inside OnClickListener of any button, just add these lines:-

Here you use VibrationEffect.createOneShot to make a solitary vibration impact, at that point you pass the value (1000) as the length of the vibration and the VibrationEffect.DEFAULT_AMPLITUDE is used to make the device vibrate with  the default settings and default strength of the device.

At any point if you want to cancel the vibration, you can simply use the vibrator.cancel() method for that purpose.

Note:- You will also need to add permission in the AndroidManifest.xml file. Simply open it and add this line:-

A sample image for vibrator in action is shown in the below picture. The button when clicked will make your device vibrate for 1000ms.

The Full Java Code along with the XML layout for the above example is shown below:-

  • First Create a new project in Android Studio
  • File ⇒ New Android ⇒ Application Project
  • Then Open src -> package -> MainActivity.java and then add following code :

JAVA (MainActivity.java)

  •  Now Open res -> layout -> activity_main.xml and then add following code :

XML (activity_main.xml)

You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project. You can also try to play with these other settings on your own and see the corresponding changes accordingly. There are a variety of properties available which can be changed to make your own customized vibration pattern as per your need.

Output:

Finally, run this project.

This is how Android Vibrate Device Code look like.

Vibrate Device Example for Android Studio

For a more detailed guide, you can also visit android’s official guide below:-

https://developer.android.com/reference/android/os/Vibrator

Comment down below if you are facing any problems.

 

Also Read:-

Leave a Reply

Your email address will not be published. Required fields are marked *