簡體   English   中英

Android中觸摸時的連續振動

[英]Continuous Vibration on Touch in android

我希望觸摸時不斷振動,直到從視圖中抬起手指為止。我使用以下代碼在畫布上進行振動

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

但是振動器不能連續播放,它是如何完成的

首先,您始終必須以毫秒為單位指定振動時間。 因此,您可以為振動設置較長的時間,並在ACTION_UP事件中停止振動。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM