Reputation: 1560
Help please. Here is what I am trying to achieve, I have this button that when I click it will vibrate phone on depending on how long you press the button.
like you hold the button for 5 seconds the vibrate will be 5 seconds.
just like a throttle
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.start);
b.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
while((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN){
vb.vibrate(100);
}
return false;
}
});
}
in my code the vibrate is like this it stops every 100 ms. also it crashes the phone
la la la la la la la la
I want to achieve a vibrate that would be something like this. the longer you will click and hold the longer it will vibrate
laaaaaaaaaaaaaaaaaaaaaaaaaaa
Upvotes: 0
Views: 336
Reputation: 4528
import android.os.Vibrator;
Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
public boolean onTouch(View v, MotionEvent event) {
boolean isReleased = event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL;
boolean isPressed = event.getAction() == MotionEvent.ACTION_DOWN;
if (isReleased) {
// do whatever you want
} else if (isPressed) {
v.vibrate(500);
}
return false;
}
Note:
Don't forget to include permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.VIBRATE"/>
Upvotes: 0
Reputation: 2566
You have code there to start the vibration. You can increase the duration to something that is unrealistic for someone to hold their finger down for (10 min?).
When they lift their finger call cancel
public boolean onTouch(View v, MotionEvent event) {
Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN){
vb.vibrate(1000*60*10);//10mins
return true;
}
if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP){
vb.cancel();
return false;
}
Upvotes: 3