Vibrate with your android

To make your app make the phone vibrate you’ll need 2 things:

  • handling code to control the vibrator
  • permission from the system so your app can mangle with a piece of the phone’s hardware (in this case the vibrator).

First let’s cover the permission part. In your manifest.xml, add a uses-permission element:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.VIBRATE" />
...
</manifest>

That’s it. Simple. Now let’s see the actual code needed to activate the vibration from code:

Vibrator myvib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
myvib.vibrate(50);

The code above just instantiates an object “myvib” of type Vibrator and then launches method “vibrate”. The argument for vibrate is the time in milliseconds that the vibrator shall be active, in this case 50 milliseconds. Note that the argument is of type Long.

Advertisements