长按按钮振动设备

时间:2013-06-16 21:27:36

标签: android android-vibration

只要用户点击按钮,我希望设备振动。如果用户长按该按钮,则只要用户点击并按住该设备就会振动。这是我实施的,但它适用于特定的时间段。

final Button button = (Button) findViewById(R.id.button1);

button.setOnLongClickListener(new OnLongClickListener() {   

    @Override
    public boolean onLongClick(View v) {
        if(v==button){
            Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vb.vibrate(1000);
       }                
       return false;
    }
});

2 个答案:

答案 0 :(得分:1)

实现ontouch侦听器并在事件中执行此操作

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

    //int action = event.getAction();
    switch (event.getAction()){
    case MotionEvent.ACTION_DOWN:
       // put your code here


    break;

答案 1 :(得分:1)

要振动无限制,您可以使用振动模式:

// 0 - start immediatelly (ms to wait before vibration)
// 1000 - vibrate for 1s
// 0 - not vibrating for 0ms
long[] pattern = {0, 1000, 0};
vb.vibrate(pattern, 0);

可以使用以下方法取消振动:

vb.cancel();

onTouch事件 - ACTION_DOWN上开始振动,停止ACTION_UP上的振动

编辑:最终工作代码:

    final Button button = (Button) findViewById(R.id.button1);
    button.setOnTouchListener(new OnTouchListener() {
        Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    long[] pattern = {0, 1000, 0};
                    vb.vibrate(pattern, 0);
                    break;
                case MotionEvent.ACTION_UP:
                    vb.cancel();
                    break;
            }
            return false;
        }
    });