Thursday, 31 May 2012

Program Android Vibrator

android.os.Vibrator operates the vibrator on the device.

Program Android Vibrator


Your code call getSystemService(AndroidVibratorActivity.VIBRATOR_SERVICE) to retrieve a Vibrator for interacting with the vibration hardware. In the example, touch on button1 to generate vibration for 500ms. Touch and hold on button2 to generate vibration for max 1 second, or release to stop.

You have to modify AndroidManifest.xml to add permission of "android.permission.VIBRATE".

package com.exercise.AndroidVibrator;

import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class AndroidVibratorActivity extends Activity {

Button buttonVibrate1, buttonVibrate2;

Vibrator myVibrator;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonVibrate1 = (Button)findViewById(R.id.buttonVibrate1);
buttonVibrate2 = (Button)findViewById(R.id.buttonVibrate2);

myVibrator = (Vibrator)getSystemService(AndroidVibratorActivity.VIBRATOR_SERVICE);

buttonVibrate1.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myVibrator.vibrate(500);
}});

buttonVibrate2.setOnTouchListener(new OnTouchListener(){

@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();

if(action == MotionEvent.ACTION_DOWN){
myVibrator.vibrate(1000);
}else if(action == MotionEvent.ACTION_UP){
myVibrator.cancel();
}

return true;
}});

}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

<Button
android:id="@+id/buttonVibrate1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Vibrate for 500ms" />
<Button
android:id="@+id/buttonVibrate2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Touch to Vibrate (max. 1 sec.)" />

</LinearLayout>


Next:
- Vibrate with a given pattern


No comments:

Post a Comment