Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaHow to Vibrate a Device Programmatically in Android?

How to Vibrate a Device Programmatically in Android?

Hepatic feedback 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




<?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>


Output UI:

 Vibrate a Device Programmatically in Android

Step 3: Invoking Vibrate permission inthe  AndroidManifest file

The vibration of the device needs permission. To invoke the following code inside the AndroidManifest file.

XML




<?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>


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


Kotlin




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;
 
class MainActivity : AppCompatActivity() {
    // buttons for all the types of the vibration effects
    var bNormalVibration: Button? = null
    var bClickVibration: Button? = null
    var bDoubleClickVibration: Button? = null
    var bTickVibration: Button? = null
    var bHeavyClickVibration: Button? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // get the VIBRATOR_SERVICE system service
        val vibrator = getSystemService<Any>(Context.VIBRATOR_SERVICE) as Vibrator
 
        // 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(object : OnClickListener() {
            fun onClick(v: View?) {
                val vibrationEffect1: VibrationEffect
 
                // this is the only type of the vibration which requires system version Oreo (API 26)
                if (Build.VERSION.SDK_INT >= 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(object : OnClickListener() {
            fun onClick(v: View?) {
 
                // this type of vibration requires API 29
                val vibrationEffect2: VibrationEffect
                if (Build.VERSION.SDK_INT >= 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(object : OnClickListener() {
            fun onClick(v: View?) {
                val vibrationEffect3: VibrationEffect
 
                // this type of vibration requires API 29
                if (Build.VERSION.SDK_INT >= 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(object : OnClickListener() {
            fun onClick(v: View?) {
                val vibrationEffect4: VibrationEffect
 
                // this type of vibration requires API 29
                if (Build.VERSION.SDK_INT >= 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(object : OnClickListener() {
            fun onClick(v: View?) {
                val vibrationEffect5: VibrationEffect
 
                // this type of vibration requires API 29
                if (Build.VERSION.SDK_INT >= 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)
                }
            }
        })
    }
}
//This code is written by Ujjwal Kumar Bhardwaj


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?

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments