How to Vibrate a Device Programmatically in Android? - GeeksforGeeks

23 Feb, 2021
Hepatic feedbacks are also considered when it comes to user experience. So in this discussion, it’s been discussed various types of haptics or the types of vibration of the device. For example, click haptics or long-press button haptics. There five different types of vibration modes in haptic feedback discussed are:
Default vibration of the deviceClick effect vibrationDouble click effect vibrationHeavy click effect vibrationTick effect vibration
Default vibration of the device
Click effect vibration
Double click effect vibration
Heavy click effect vibration
Tick effect vibration
Note that we are going to implement this project using the Java language. 
Step 1: Create an empty activity Android studio project
Create an empty activity android studio project.
Refer to Android | How to Create/Start a New Project in Android Studio?
Note that select Java as the programming language.
Step 2: Working with the activity_main.xml
In this discussion, four different types of haptics are discussed.
So to generate that haptics there are four different buttons are included in the layout. Invoke the following code inside the activity_main.xml file.
Make sure to give appropriate IDs for all the buttons to handle them in the MainActivity.java file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity"    tools:ignore="HardcodedText">      <!--Button to generate normal vibration-->    <Button        android:id="@+id/normalVibrationButton"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_marginTop="64dp"        android:backgroundTint="@color/colorPrimary"        android:text="NORMAL VIBRATION"        android:textColor="@android:color/white" />      <!--Button to generate click vibration-->    <Button        android:id="@+id/clickVibrationButton"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/normalVibrationButton"        android:layout_centerHorizontal="true"        android:layout_marginTop="8dp"        android:backgroundTint="@color/colorPrimary"        android:text="CLICK VIBRATION"        android:textColor="@android:color/white" />      <!--Button to generate double click vibration-->    <Button        android:id="@+id/doubleClickVibrationButton"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/clickVibrationButton"        android:layout_centerHorizontal="true"        android:layout_marginTop="8dp"        android:backgroundTint="@color/colorPrimary"        android:text="DOUBLE CLICK VIBRATION"        android:textColor="@android:color/white" />      <!--Button to generate tick vibration-->    <Button        android:id="@+id/tickVibrationButton"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/doubleClickVibrationButton"        android:layout_centerHorizontal="true"        android:layout_marginTop="8dp"        android:backgroundTint="@color/colorPrimary"        android:text="TICK VIBRATION"        android:textColor="@android:color/white" />      <!--Button to generate heavy click vibration-->    <Button        android:id="@+id/heavyClickVibrationButton"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/tickVibrationButton"        android:layout_centerHorizontal="true"        android:layout_marginTop="8dp"        android:backgroundTint="@color/colorPrimary"        android:text="HEAVY CLICK EFFECT VIBRATION"        android:textColor="@android:color/white" />  </RelativeLayout>
Output UI:
Step 3: Invoking Vibrate permission in AndroidManifest file
The vibration of the device needs permissions. To invoke the following code inside the AndroidManifest file.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.adityamshidlyali.vibrationsinandroid">      <!--vibrate permission which needs to be invoked as we hard         accessing the vibrator hardware of the device-->    <uses-permission android:name="android.permission.VIBRATE" />      <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>  </manifest>
Step 4: Working with the MainActivity.java file
As it is said that there are five different kinds of vibrations. For those five kinds of vibrations, there are constants for each of them. Those are:
DEFAULT_AMPLITUDE -> for default vibration of the device
EFFECT_CLICK -> for single click haptic
EFFECT_DOUBLE_CLICK -> for double click of the view
EFFECT_HEAVY_CLICK -> for heavy click effect of the view
EFFECT_TICK -> for tick effect vibration
Invoke the following code inside the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.os.Bundle;import android.os.VibrationEffect;import android.os.Vibrator;import android.view.View;import android.widget.Button;  public class MainActivity extends AppCompatActivity {      // buttons for all the types of the vibration effects    Button bNormalVibration, bClickVibration, bDoubleClickVibration, bTickVibration, bHeavyClickVibration;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // get the VIBRATOR_SERVICE system service        final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);          // register all of the buttons with their IDs        bNormalVibration = findViewById(R.id.normalVibrationButton);        bClickVibration = findViewById(R.id.clickVibrationButton);        bDoubleClickVibration = findViewById(R.id.doubleClickVibrationButton);        bTickVibration = findViewById(R.id.tickVibrationButton);        bHeavyClickVibration = findViewById(R.id.heavyClickVibrationButton);          // handle normal vibration button        bNormalVibration.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                final VibrationEffect vibrationEffect1;                                // this is the only type of the vibration which requires system version Oreo (API 26)                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {                      // this effect creates the vibration of default amplitude for 1000ms(1 sec)                    vibrationEffect1 = VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE);                      // it is safe to cancel other vibrations currently taking place                    vibrator.cancel();                    vibrator.vibrate(vibrationEffect1);                }            }        });          // handle click vibration button        bClickVibration.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                  // this type of vibration requires API 29                final VibrationEffect vibrationEffect2;                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {                      // create vibrator effect with the constant EFFECT_CLICK                    vibrationEffect2 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK);                      // it is safe to cancel other vibrations currently taking place                    vibrator.cancel();                      vibrator.vibrate(vibrationEffect2);                }            }        });          // handle double click vibration button        bDoubleClickVibration.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                  final VibrationEffect vibrationEffect3;                                // this type of vibration requires API 29                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {                      // create vibrator effect with the constant EFFECT_DOUBLE_CLICK                    vibrationEffect3 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK);                      // it is safe to cancel other vibrations currently taking place                    vibrator.cancel();                      vibrator.vibrate(vibrationEffect3);                }            }        });          // handle tick effect vibration button        bTickVibration.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                final VibrationEffect vibrationEffect4;                                // this type of vibration requires API 29                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {                      // create vibrator effect with the constant EFFECT_TICK                    vibrationEffect4 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK);                      // it is safe to cancel other vibrations currently taking place                    vibrator.cancel();                      vibrator.vibrate(vibrationEffect4);                }            }        });          // handle heavy click vibration button        bHeavyClickVibration.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                final VibrationEffect vibrationEffect5;                                // this type of vibration requires API 29                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {                      // create vibrator effect with the constant EFFECT_HEAVY_CLICK                    vibrationEffect5 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_HEAVY_CLICK);                      // it is safe to cancel other vibrations currently taking place                    vibrator.cancel();                      vibrator.vibrate(vibrationEffect5);                }            }        });    }}
The output should be tested on the physical android device. To know how to set up a physical android studio refer to How to Run the Android App on a Real Device?
Android-Misc
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Retrofit with Kotlin Coroutine in Android
Flutter - Custom Bottom Navigation Bar
How to Post Data to API using Retrofit in Android?
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
HashMap in Java with Examples