Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vibrate when hold down button

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.

like image 790
Lucas Avatar asked Apr 24 '11 14:04

Lucas


1 Answers

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.

like image 195
Bipin Vayalu Avatar answered Sep 20 '22 15:09

Bipin Vayalu