振动直到按下按钮,当按钮未按下(或手指离开)时停止振动

Vibrate until the button is pressed and stops vibrating when the button is unpressed (or the finger is taken off)

我计划以这样一种方式对按钮进行编程,即当按下按钮时振动开始并持续振动直到手指抬起或按钮未按下。

我正在为此目的使用 Touch Listener。

我的代码如下:

package com.example.vibrator;

import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Vibrator vibrator;

        vibrator = (Vibrator) getSystemService(MainActivity.VIBRATOR_SERVICE);

        Button btn = (Button) findViewById(R.id.button1);
        btn.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();

                if (action == MotionEvent.ACTION_DOWN) {
                    vibrator.vibrate(60000);
                } else if (action == MotionEvent.ACTION_UP) {
                    vibrator.cancel();
                }

                return true;
            }
        });
    }
}

此代码中的问题是它一直在振动,当手指向上时振动不会停止或取消。

P.S 我已经使用清单中的权限

编辑:更正代码:

试试这个:

int action = event.getActionMasked();

if (action == MotionEvent.ACTION_DOWN) {
    long[] pattern = { 0, 200, 0 }; //0 to start now, 200 to vibrate 200 ms, 0 to sleep for 0 ms.
    vibrator.vibrate(pattern, 0); // 0 to repeat endlessly.
} else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
    vibrator.cancel();
}