Vibrate when hold down button

Lucas picture Lucas · Apr 24, 2011 · Viewed 29.8k times · Source

I am making an app where the user holds down a button to make the phone vibrate and i'm not sure how to make it so only when the button is being held down it vibrates, my code so far is.

package one.two.bn;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;



    public class Vb extends Activity {
            /** Called when the activity is first created. */
        private Button button1;
        private Vibrator vibrator;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            button1 = (Button)findViewById(R.id.button1);
            button1.setOnClickListener(new View.OnClickListener() {
            Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);    
        public void onClick(View v) {
                if(v==button1){ 
                vibrator.vibrate(300000);           
        }
    }

If any on can help thanks a lot.

Answer

Bipin Vayalu picture Bipin Vayalu · Apr 24, 2011

Try this code

Vibrator vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE) ;

Then in the OnClickListener of your button:

vibe.vibrate(50); // 50 is time in ms

And dont forget you need to add the permission to the manifest (after the </application> tag):

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

I also agree with Tim, because onTouchListener is called before on click so it is give best output for your app.