Related Articles

Related Articles

How to Vibrate a Device Programmatically in Android?
  • Last Updated : 24 Nov, 2020

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:

  1. Default vibration of the device
  2. Click effect vibration
  3. Double click effect vibration
  4. Heavy click effect vibration
  5. Tick effect vibration

Note that we are going to implement this project using the Java language. 

Steps to implement haptic feedbacks in Android

Step 1: Create an empty activity Android studio project

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



filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    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>

chevron_right


Output UI:

 Vibrate a Device Programmatically in Android

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
    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>

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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);
                }
            }
        });
    }
}

chevron_right


Output:

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?

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :