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

标签 java android vibration

我打算对一个按钮进行编程,使其在按下按钮时开始振动并持续振动,直到手指抬起或松开按钮。

为此我正在使用 OnTouchListener。

我的代码如下:

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

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

附言我已经使用了 list 中的权限。

最佳答案

编辑:更正代码:

试试这个:

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

关于java - 振动直到按下按钮,当按钮未按下(或手指离开)时停止振动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28599455/

相关文章:

java - 如何比较列表中的最小值?

java - 使用 Protocol Buffer 序列化/反序列化独立整数

Android actionbar 子菜单项显示在 actionbar 顶部而不是栏下方

javascript - Navigator.vibrate() 在笔记本电脑上不起作用

java - 对远程 Web 服务的 Spring Boot http 调用

java - 如何在没有按钮的情况下导航回主要 Activity

android - 无法实例化服务

android - 如何格式化 strings.xml 中的长文本?

iphone - 设备上的 MonoTouch - 启动时振动?

android - Flutter:在设备上振动非标准时间长度