Search code examples
androidvibration

Continuous Vibration on Touch in android


I want to vibrate continuously on touch until I raise the finger from the view.I used the following code for vibration on canvas

public class DrawFunny extends Activity implements OnTouchListener  {
private float x;
private float y;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    MyCustomPanel view = new MyCustomPanel(this);

    ViewGroup.LayoutParams params = 
                        new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT,
                                                   LayoutParams.FILL_PARENT);
    addContentView(view, params);
    view.setOnTouchListener(this);

}
private class MyCustomPanel extends View {

    public MyCustomPanel(Context context) {
        super(context);

    }
    @Override
    public void draw(Canvas canvas) {

        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(6);

        canvas.drawLine(10,10,50,50,paint);
        paint.setColor(Color.RED);

        canvas.drawLine(50, 50, 90, 10, paint);
        canvas.drawCircle(50, 50, 3, paint);

        canvas.drawCircle(x,y,3,paint);

    }
}
public boolean onTouch(View v, MotionEvent event) {
  Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vb.vibrate(100);
    x = event.getX();
    y = event.getY();

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:

        System.out.println("ACTION_DOWN");

        return true;
    case MotionEvent.ACTION_MOVE:
        System.out.println("ACTION_MOVE");

        break;
    case MotionEvent.ACTION_UP:
        System.out.println("ACTION_UP");

        break;
    default:
        return false;
    }
    v.invalidate();
    return true;
}
}

But the vibrator not playing continuously how is it done


Solution

  • First of all, you always have to specify the vibration time in millis. So you can set a long time for the vibration and stop the vibration in the ACTION_UP event. For example:

    public boolean onTouch(View v, MotionEvent event) {
        Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            vb.vibrate(10000); // 10 seconds
            System.out.println("ACTION_DOWN");
    
            return true;
        case MotionEvent.ACTION_MOVE:
            System.out.println("ACTION_MOVE");
    
            break;
        case MotionEvent.ACTION_UP:
            System.out.println("ACTION_UP");
            vb.cancel(); // Stop the vibration
            break;
        default:
            return false;
        }
    
        return true;
    }