How to programmatically vibrate a phone in Android

In this android programming source code example, we are going to make phone vibrate in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to make phone vibrate in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".DeviceFeatures.DeviceFeaturesActivity18">

    <Button
        android:id="@+id/vibrate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Vibrate Phone"
        android:textColor="#ffffff"
        android:background="@color/colorAccent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;

import com.bluapp.androidview2.R;

public class DeviceFeaturesActivity18 extends AppCompatActivity {
    private Button vibrate;
    private Vibrator vibrator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_features18);
        vibrate = (Button) findViewById(R.id.vibrate);
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    vibrator.vibrate(VibrationEffect.createOneShot(600, VibrationEffect.DEFAULT_AMPLITUDE));
                } else {
                    vibrator.vibrate(600);
                }
            }
        });
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.VIBRATE" />

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment