Vibrate the phone for a given time or a certain pattern

1 vote · 2 comments

This code vibrates the phone for 1000 milliseconds. After getting the vibrator service with Context.getSystemService we call Vibrator.vibrate for a given time in milliseconds.

raw ·
copy
· download
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // 1. Vibrate for 1000 milliseconds long milliseconds = 1000; v.vibrate(milliseconds); // 2. Vibrate in a Pattern with 500ms on, 500ms off for 5 times long[] pattern = { 500, 300 }; v.vibrate(pattern, 5);
Add a comment

2 Comments

For this to work, you will have to add the android.permission.VIBRATE permission to your Manifest.xml

Reply · Aug. 27, 2009, 5:26 p.m.

In Android 2.2 the line v.vibrate(pattern, 5); causes some kind of 'index out of bounds' exception as the 5 is an index into pattern. The 5 is not the number of times to repeat.
Try: v.vibrate(pattern, -1); // no repeat

or

long[] pattern = { 0, 200, 500, 200, 500, 200, 500 }; v.vibrate(pattern, 1); // repeat until v.cancel();

Reply · March 15, 2011, 12:03 a.m.