Android Program to Vibrate Phone
Android Sample Codes Uncategorized

Android Program to Vibrate Phone

Android Program to Vibrate Phone, in this post we will learn how to vibrate your Android phone. Here we are using android Vibrator class that operates the vibrator on the device.

Vibrate for a Given Length of Time

Before we proceed Click here to know how to install Android studio in Ubuntu. In order to vibrate your android phone, first we need to create object of android Vibrator class.

// Get instance of Vibrator from current Context

Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 200 milliseconds

v.vibrate(200);

Vibrate Works On Play & Pause Pattern

We can Vibrate a phone for 200 ms then pause for 100 ms and again vibrate for 200 ms then our pattern becomes : {200, 100, 200};

Vibrator treats first element of an array for delay in ms before starts vibrating.  Which means your device start vibrating after array[0] ms. Suppose if you don’t want any delay then the array becomes.

 {0, 200, 100, 200};
Consider our pattern as follows
long pattern[] = {0,400,800,600,800,800,800,1000};
// Vibrate the device using a pattern and repeat 3 times
v.vibrate(pattern,0);

The first argument of vibrate method is an array of ints that are the durations for which to turn on or off the vibrator in milliseconds.

The second argument is the index in the pattern array at which to repeat vibration, or -1 if you don’t want to repeat.

The first value in the pattern array indicates the number of milliseconds to wait before turning the vibrator on.

The next value indicates the number of milliseconds for which to keep the vibrator on before turning it off.

Subsequent values alternate between durations in milliseconds to turn the vibrator off or to turn the vibrator on.

By passing -1 to the vibrate()method we are asking to play it just once. If we want to repeat this pattern we can just pass 0 instead of -1.

// 0 : Repeat this pattern from 0th element.
v.vibrate(pattern, 0);

To cancel vibration at any time call 

v.cancel()

Repeat vibration pattern from specific index?

Suppose you want to repeat the vibration or repeat the pattern from a specific index we can pass the index of the array as shown below.

// 3 : Repeat this pattern from 3rd element of an array pattern
v.vibrate(pattern, 3);

Play Vibration Exactly Once

If we don’t want to repeat the pattern , pass -1 as the repeating position which would be out of bounds and hence it would stop.

// -1 : Play exactly once
v.vibrate(pattern, -1);

Add vibrate permission in Androidmanifest.xml

In order to work vibrator program in your device, we need to set vibrate permission in your phone.

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

Android Program to Vibrate Phone

I have created three button in the layout for vibrate phone. The first button for vibrate Phone, second button for vibrate phone based on some pattern and the third button for cancel the vibration.

Android Program to Vibrate Phone

 

The layout for android program to vibrate phone is shown below.

activity_main.xml
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical">
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:textColor="#000"
        android:padding="20dp"
        />
    <Button
        android:id="@+id/btn_on"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click Here To Vibrate !!"
        />
    <Button
        android:id="@+id/btn_repeat"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click Here To Repeat Vibration !!"
        />
    <Button
        android:id="@+id/btn_off"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click Here To Off Vibration !!"
       />
</LinearLayout>

The activity file MainActivity is modified for vibrate phone.

MainActivity.java
package com.example.androidprogramtovibratethedevice;

import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView TxtView;
    private Button BtnOn;
    private Button BtnRepeat;
    private Button BtnOff;
    private Vibrator v;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Get the widgets reference from XML layout
        TxtView = (TextView) findViewById(R.id.tv);
        BtnOn = (Button) findViewById(R.id.btn_on);
        BtnRepeat = (Button) findViewById(R.id.btn_repeat);
        BtnOff = (Button) findViewById(R.id.btn_off);
        // Initialize a new instance of system Vibrator
        v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        // Check whether device hardware has a Vibrator
        if(v.hasVibrator()){
            TxtView.setText("Yes !!!!!!! Your Device has a Vibrator.");
        }
        // Set a click listener for Vibrate button
        BtnOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Vibrate the device for a specified time
                v.vibrate(5000); // 5 seconds
            }
        });
        // Set a click listener for repeat button
        BtnRepeat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Vibrate the device repeatedly.
                // Set a pattern for vibration
                long pattern[] = {0,400,800,600,800,800,800,1000};

                // Vibrate the device using a pattern and repeat 3 times
                v.vibrate(pattern,0);
            }
        });
        // Set a click listener for vibration off button
        BtnOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Cancel the vibration
                v.cancel();
            }
        });
    }

}
AndroidManifest.xml

Add vibrate permission in the AndroidManifest file as shown below.

AndroidManifest.xml
 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidprogramtovibratethedevice">
    <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>

Output of  Android Program to Vibrate Phone is when you click on the first button it will vibrate for 5 seconds, when you click on the second button it will vibrate based on the pattern in the array and when you click on the third button it will cancel the vibration.

 

Leave a Reply

Your email address will not be published.