Android – Vibrate Code

Firstly, the Manifest file must include the permissions for VIBRATE:

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

The actual code is:


Vibrator  myVibratorService = (Vibrator) getSystemService("vibrator");
 myVibratorService.vibrate(2000);

Note – to debug this I actually used this:


try {
 Vibrator  myVibratorService = (Vibrator) getSystemService("vibrator");

 if (myVibratorService != null) {
 myVibratorService.vibrate(2000);

 } else {
 Log.d("UHTestApp", "service == null");
 }
 }
 catch (Exception e) {
 String msg = "Exc: " + e.getMessage();

 //String msg = "Vibrate Selected";
 AlertDialog.Builder builder = new AlertDialog.Builder(this);
 builder.setMessage(msg)
 .setCancelable(false)
 .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int id) {
 dialog.cancel();
 }
 });
 AlertDialog alert = builder.create();
 alert.show();
 }

The first part encapsulates everything in a try…catch, which really does help when things don’t work as expected. The catch is just a way of getting amessage box to pop-up with details.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s