I am planing to programe a button in such a way that when button is pressed vibration start and keeps on vibrating untill the finger is up or button is unpressed.
我正在计划按钮按钮,按下按钮振动开始并继续振动,直到手指向上或按钮未按下。
I am using on Touch Listener for this purpose.
我正在使用Touch Listener来实现此目的。
My code is as follows:
我的代码如下:
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;
}
});
}
}
The problem in this code is that it keeps on vibrating and when the finger is up the vibration does not stop or cancelled.
此代码中的问题是它继续振动,当手指向上时,振动不会停止或取消。
P.S i have used the permission in manifest
P.S我已经使用了清单中的许可
1 个解决方案
#1
5
EDIT: corrected code:
编辑:更正的代码:
try this:
尝试这个:
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();
}
#1
5
EDIT: corrected code:
编辑:更正的代码:
try this:
尝试这个:
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();
}