Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Making the Device Vibrate

Author: Rachee Singh
Published? true
FormatLanguage: WikiFormat

Problem:

Through your application, you wish to notify the user of an event by means of device's vibration.

Solution:

Using Notifications to set a vibration pattern.

Discussion:

To use device vibration, include this permission in the AndroidManifest file:


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

In the Java code, we need to get an instance of the NotificationManager class and of Notification class:


NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
Notification notification = new Notification();

To set a pattern for the vibration, assign a sequence of long values (time in millisecond) to Notification's vibrate property. This sequence represents the time for which the device will be silent and the time for which it will vibrate, alternatively, and should be an even number of long values. For instance: The pattern used in this example will cause the device to vibrate for 1 second then pause for 1 second then vibrate again for 1 second and so on.


notification.vibrate = new long[]{1000, 1000, 1000, 1000, 1000, 1000}; 
notificationManager.notify(0, notification);

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LZjJiMTU5MzEtYzk3NC00NTcxLWE0NDAtMDVjY2I3ZWFmMGI3&hl=en_US&authkey=CJ2SjpAC.

Download:

The source code for this project is in the Android Cookbook repository at http://github.com/IanDarwin/Android-Cookbook-Examples, in the subdirectory Vibrate.
No records found.