Android vibrate example

In this post, we will learn about Android vibrate service which is available from version 1.0 of Android, the SDK has included necessary features in vibrate service that gives developers to use it creatively.

Why vibrate service?

Vibrate service improves the user experience by providing haptic feedback to users or to interact with users even when phone volume is low or set to zero.

We can make android phone to vibrate in following three ways:

  1. Vibrate for a given length of time
  2. Vibrate on a given pattern
  3. Vibrate repeatedly until cancelled

Subscribe and download free ebook
Email:
Vibrate for a Given Length of Time:

When user touches the application, and you would like to give haptic feedback, this is the right way of using vibrate service. I will make the phone to vibrate for 300 milliseconds as a good single touch feedback.

// Get instance of Vibrator from current Context
Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 300 milliseconds
mVibrator.vibrate(300);
Vibrate on a Given Length of Time:

This type of vibration is useful when you need to provide a user with one-time notification such as receiving a text message, receiving facebook post update etc. In the below code, I used SOS pattern:

// Get instance of Vibrator from current Context
Vibrator mVibrator  = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// This code snippet will cause the phone to vibrate "SOS" in Morse Code
// In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash"
// There are pauses to separate dots/dashes, letters, and words
// The following numbers represent millisecond lengths
int dot = 200;      // Length of a Morse Code "dot" in milliseconds
int dash = 500;     // Length of a Morse Code "dash" in milliseconds
int short_gap = 200;    // Length of Gap Between dots/dashes
int medium_gap = 500;   // Length of Gap Between Letters
int long_gap = 1000;    // Length of Gap Between Words
long[] pattern = {
    0,  // Start immediately
    dot, short_gap, dot, short_gap, dot,    // s
    medium_gap,
    dash, short_gap, dash, short_gap, dash, // o
    medium_gap,
    dot, short_gap, dot, short_gap, dot,    // s
    long_gap
};
// Only perform this pattern one time (-1 means "do not repeat")
mVibrator.vibrate(pattern, -1);
Vibrate repeatedly until cancelled:

This type of vibration is useful when you need to notify the user for immediate attention, such as incoming phone call etc.

// Get instance of Vibrator from current Context
Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Start immediately
// Vibrate for 200 milliseconds
// Sleep for 0 milliseconds
long[] pattern = { 0, 200, 0 };

// The "0" means to repeat the pattern starting at the beginning and -1 means do not stop
// You will vibrate for your pause times and pause for your vibrate times !
mVibrator.vibrate(pattern, 0);
Add vibrate permission in Androidmanifest.xml:
<uses-permission android:name="android.permission.VIBRATE" />

Here I demonstrated all the three ways of using vibrate service with a simple example(shown below):

Let us start creating the application.

Quick Links

Project Structure

  • Create new android project [File >> New >> Android Project] with project name VibratorExample
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘com.prgguru.android’
  • Click finish

Code Listings

Layout XML:

Add the following xml in the main.xml present under /res/layout folder of the project:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:ignore="HardcodedText" >
 <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:gravity="center"
        android:text="Vibrator for 300 MS" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dip"
        android:text="Vibrate" />
     <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:gravity="center"
        android:text="Vibrator on SOS Pattern" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dip"
        android:text="Vibrate" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:gravity="center"
        android:text="Vibrate until I cancel" />

    <Button
        android:id="@+id/btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dip"
        android:text="ON" />

</LinearLayout>

VibratorExampleActivity.java:
Logic behind the application is given below:

package com.prgguru.android;

import android.os.Bundle;
import android.os.Vibrator;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class VibratorExampleActivity extends Activity {
	Button vib1;
	Button vib2;
	Button vib3;

	Vibrator mVibrator;

	int dot = 200; // Length of a Morse Code "dot" in milliseconds
	int dash = 500; // Length of a Morse Code "dash" in milliseconds
	int short_gap = 200; // Length of Gap Between dots/dashes
	int medium_gap = 500; // Length of Gap Between Letters
	int long_gap = 1000; // Length of Gap Between Words

	long[] pattern = { 0, // Start immediately
			dot, short_gap, dot, short_gap, dot, // s
			medium_gap, dash, short_gap, dash, short_gap, dash, // o
			medium_gap, dot, short_gap, dot, short_gap, dot, // s
			long_gap };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// Find button 1
		vib1 = (Button) findViewById(R.id.btn1);
		// Find button 2
		vib2 = (Button) findViewById(R.id.btn2);
		// Find button 3
		vib3 = (Button) findViewById(R.id.btn3);
		// Create Vibrator instance for current context
		mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

		// Click Listener for button1
		vib1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Vibrates for 300 Milliseconds
				mVibrator.vibrate(300);
			}
		});
		// Click Listener for button2
		vib2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Vibrates on SOS pattern
				mVibrator.vibrate(pattern, -1);
			}
		});
		// Click Listener for button3
		vib3.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {				
				Button b = (Button) v;
				//Vibrates until you cancel it
				if (b.getText().toString().equalsIgnoreCase("ON")) {
					b.setText("OFF");
					mVibrator.vibrate(new long[] { 0, 200, 0 }, 0);
				} else {
					b.setText("ON");
					mVibrator.cancel();
				}
			}
		});
	}

	@Override
	public void onDestroy() {
		//Cancel vibration when the application is about to close
		if (mVibrator != null)
			mVibrator.cancel();
		super.onDestroy();
	}
}

Demo

Congratulations, We are done.
Let us test the application:
Right click on the project >> Run as >> Android application >> Choose emulator or device
You could see this screen:

 

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

 

Reference:

Android Vibrator service

I hope you enjoyed the post!! :)

Suggested posts for further reading


Feedback

If you like this post, please do click 'Appreciate Badge'

*You can "Appreciate" this post only once from this IP


Author: Android Guru

Share This Post On
  • Patel Rumit

    veRy good example… :)

  • badruduja

    good example

  • Vishal

    Awesome example…by this coding i also became to know about MORSE CODE…Thank u guys..!

x
Subscribe and stay in touch!!

Enter your email and stay on top of things:

Your email address will not be published