In this tutorial we will learn how to enable vibration for creating alerts in your android application.

Create a new project -> Vibration.

Our Application should have access to Vibrate system call.
Hence we add the following line in our AndroidManifest.xml file.

 

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

 

We will Create a Button for user to click and enable vibration.

<Button
android:id=”@+id/vibrate”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Vibrate !!” />

 

In the Vibration.java Button, we create an event listener for the Button
we added in activity_vibration.xml file.

 

Button b1 = (Button) findViewById(R.id.vibrate);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0){

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

vibr.vibrate(800);
}
});

 

Complete code is as given below.

 

AndroidManifest.xml

<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.example.vibration”
android:versionCode=”1″
android:versionName=”1.0″ >

<uses-sdk
android:minSdkVersion=”8″
android:targetSdkVersion=”15″ />

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

<application
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
<activity
android:name=”.Vibration”
android:label=”@string/title_activity_vibration” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>

</manifest>

 

activity_vibration.xml

 

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent” >

<Button
android:id=”@+id/vibrate”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Vibrate My Phone” />

</RelativeLayout>

 

Vibration.java

 

package com.example.vibration;

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

public class Vibration extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vibration);

Button b1 = (Button) findViewById(R.id.vibrate);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0){

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

vibr.vibrate(800);
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_vibration, menu);
return true;
}
}