Android Vibrate on touch?

18,785

Solution 1

please try this :

Button b = (Button) findViewById(R.id.button1);
    b.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            Vibrator vb = (Vibrator)   getSystemService(Context.VIBRATOR_SERVICE);
            vb.vibrate(100);
            return false;
        }
    });

and add this permission to manifest.xml

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

Solution 2

According to this answer, you can perform haptic feedback (vibrate) without asking for any extra permissions. Look at performHapticFeedback method.

View view = findViewById(...)
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);

Note: I have not tested this code.

Solution 3

This will vibrate once, when user touches view (will not keep vibrating when user sliding his finger on the view!):

@Override
public boolean onTouch(View view, MotionEvent event) {

    if(event.getAction() == MotionEvent.ACTION_DOWN) {
        Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(VIBRATE_DURATION_MS);
    }
    return true;
}

And as Ramesh said, allow permission in manifest:

<uses-permission android:name="android.permission.VIBRATE"/>
Share:
18,785

Related videos on Youtube

Fofole
Author by

Fofole

Updated on June 04, 2022

Comments

  • Fofole
    Fofole almost 2 years

    I am trying to make my device vibrate when I touch an object on Screen. I am using this code:

     Vibrator v = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE); 
     v.vibrate(300);    
    

    with the permission in the manifest file but I don't seem to get any results. Any suggestions? Also, my hardware supports vibrate.

  • deepak Sharma
    deepak Sharma over 12 years
    it works fine I think you implement onTouch method on wrong widget please check again.because their is no problem with vibration code.
  • Martin Erlic
    Martin Erlic over 7 years
    I find that this one is kind of weak. Are there any stronger touch vibrations?
  • Mercury
    Mercury over 7 years
    This is nice, but when user continue moving finger, it will keep vibrating - not a good user experience - See my answer below which solves this
  • DmitryKanunnikoff
    DmitryKanunnikoff over 6 years
    Excellent! Exactly what I needed. Thank you very much.
  • Serg Burlaka
    Serg Burlaka about 4 years
    Excellent! Thanks a lot for avoiding additional permissions.