Question

Maybe someone can explain me, how to vibrate from OnLongClickListener properly. In method below the vibration is very short. If I set return false; vibration lasts for 5000ms as expected, BUT OnClickListener is fired.

How should I vibrate from OnLongClickListener for whole period, and not fire OnClickListener?

final Vibrator x = (Vibrator) getParent()
            .getSystemService(Context.VIBRATOR_SERVICE);
button.setOnLongClickListener(new OnLongClickListener() {
        @Override
    public boolean onLongClick(View v) {
        x.vibrate(5000);
        return true;
    } 
}); 
Was it helpful?

Solution

When a click event is triggered, it is passed down to the lowest handler available (unless someone interrupted). In your case, a long click event is first passed to the OnLongClickListener. If that listener returns true, it basically announces that this click event has been handled. If it returns false, it a announces that the click event was not handled by it, and that's why the event is passed along one level higher to the handler above it in the hierarchy, in your case, the OnClickListener.

That's why returning false isn't the way to go, because you do want to handle the long click event.

What about creating a background thread or an ASyncTask for the vibration itself. Something Like:

@Override
public boolean onLongClick(View v) {
    getHandler().post(new Runnable() {

        @Override
        public void run() {
            x.vibrate(5000);           
        }

    });
    return true;
} 

I didn't test the code but it should be fine.

OTHER TIPS

You could set a timer to run for the period of the vibration, and only once it has timed out, return True. A bit fudgy, but it should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top