Continuous Vibration on Touch in android

十年热恋 提交于 2020-01-14 03:28:08

问题


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


回答1:


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;
}


来源:https://stackoverflow.com/questions/24968421/continuous-vibration-on-touch-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!