Wednesday, May 21, 2014

Vibrate Android device with Example

Vibrating Android device is found effective when you wanted to get notified on the incoming connection in various cases like, user cannot hear a ringtone or he wants to get notified silently. Its a very basic feature found in all mobile phones. Lets see how to vibrate an android device programatically. Its just two lines of code.




Vibrate pattern

 public abstract void vibrate (long[] pattern, int repeat) 

Pattern for vibration is nothing but an array of duration's to turn ON and OFF the vibrator in milliseconds. The first value 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, alternates between ON and OFF.

long pattern[]={0,100,200,300,400};

If you feel not to have repeats, just pass -1 for 'repeat'. To repeat patterns, just pass the index from where u wanted to start. I wanted to start from 0'th index and hence I am passing 0 to 'repeat'.
vibrator.vibrate(pattern, 0);

Android manifest permission for Vibration

Last but not the least add permission to Android manifest file.

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

MainActivity.java
import android.os.Bundle;
import android.os.Vibrator;
import android.app.Activity;
import android.content.Context;
import android.view.View;

public class MainActivity extends Activity {
 public Vibrator vibrator;

  @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 }

  public void startVibrate(View v) {
  long pattern[] = { 0, 100, 200, 300, 400 };
  vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  vibrator.vibrate(pattern, 0);
 }

  public void stopVibrate(View v) {
  vibrator.cancel();
 }
}

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


Source Code of this application:

AndroidVibrateExample.zip



No comments:

Post a Comment