android 振动直至按下按钮,并在未按下按钮(或手指移开)时停止振动

t3irkdon  于 2022-11-20  发布在  Android
关注(0)|答案(1)|浏览(122)

我正计划以这样一种方式编程一个按钮,当按钮被按下时,振动开始并不断振动,直到手指向上或按钮未按下。
我将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;
            }
        });
    }
}

这个代码的问题是它一直在振动,当手指向上时,振动不会停止也不会取消。
P.S.我已经使用了清单中的权限。

wixjitnu

wixjitnu1#

EDIT:更正代码:

试试这个:

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

相关问题