Permissions Journey: VIBRATE

Public on May 24, 2009
Lets jump to Vibrate Permissions on Android. By default everything you need to know could be found at the Vibrator Class. To give an example of using vibrate:

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

Archos 5 32 GB Internet Tablet with Android

Main.xml Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
>
  <Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/simpleBtn"
    android:text="Simple Vibrate"
  />
  <Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/patternBtn"
    android:text="Pattern Vibrate"
  />
  <Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/cancelBtn"
    android:text="Cancel Vibrate"
  />
</LinearLayout>


Main.java
private Button simpleBtn;
private Button patternBtn;
private Button cancelBtn;
private Vibrator vibrator;
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  simpleBtn = (Button)findViewById(R.id.simpleBtn);
  simpleBtn.setOnClickListener(this);
  patternBtn = (Button)findViewById(R.id.patternBtn);
  patternBtn.setOnClickListener(this);
  cancelBtn = (Button)findViewById(R.id.cancelBtn);
  cancelBtn.setOnClickListener(this);
  vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
}
public void onClick(View v) {
  if(v==simpleBtn){
    vibrator.vibrate(500);
  }else if(v == patternBtn){
    long[] pattern = {0L,100L,250L,1000L,250L,500L};
    vibrator.vibrate(pattern,2);
  }else{
    vibrator.cancel();
  }
}


Explanation
We create 3 buttons simpleBtn, patternBtn and cancelBtn and bind the onclick listener to the class.

First we get our vibrator service
vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

Then on our simpleBtn, we use the vibrate function and vibrate the phone for 500ms
vibrator.vibrate(500);

On our patternBtn, we use an array (long), where the array reads as 0L(off), 100L (on), 250L (off) and so on. Then after completing the first pattern we repeat the series from the 3rd value (250L(off),2 on our function, 0 based index)
long[] pattern = {0L,100L,250L,1000L,250L,500L};
vibrator.vibrate(pattern,2);


On our cancelBtn, we simple cancel the vibration we created
vibrator.cancel();

Reference
Vibrator Class
http://www.google.com/codesearch/p?hl=en#tk1mgwvuros/trunk/src/au/id/weston/scott/Sketchaetch/Sketchaetch.java&q=VIBRATOR_SERVICE&l=287

Update History
   Jan 17, 2012 - Visual Update




[Advertising]Faster Thinking - Speed up your brain


Faster Thinking Game



sentiment_satisfied Emoticon