Search code examples
androidvibrationandroid-vibration

I tried to make a simple application to let my phone vibrate


import android.content.Context;
import android.os.Vibrator;
Context context;
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATE_SERVICE);

void setup(){}

void draw(){
  v.vibrate(1000);
  noLoop();
}

PS. I gave the permissions for vibrate through the settings

So what am I doing wrong ?


Solution

  • use this

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

    instead of this

    Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATE_SERVICE);
    

    NOTE : Don't forgot to initialize your context

    UPDATE

    Vibrator.vibrate() is deprecated

    use this

    void draw(){
    
            if (Build.VERSION.SDK_INT >= 26) {
                v.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));
            } else {
                v.vibrate(1000);
            }
        } 
    

    Sample code

    import android.content.Context;
    import android.os.Build;
    import android.os.VibrationEffect;
    import android.os.Vibrator;
    
    public class Tester
    {
        Context context;
        Vibrator vibrator;
    
        public Tester(Context context) {
            this.context = context;
            vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        }
    
    
    
    
        void setup(){}
    
        void draw(){
    
            if (Build.VERSION.SDK_INT >= 26) {
                vibrator.vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
            } else {
                vibrator.vibrate(150);
            }
        }
    }
    

    call this method like this

    Tester tester= new Tester(this);
    tester.draw();