jay tandel jay tandel - 2 months ago 6
Java Question

How to trigger a method if users don't click on Button in Android after a delay of time

I am making an android application in its layout, I have 4 buttons

<Button
style="@style/Tile"
android:id="@+id/button1"
android:onClick="b1"/>

<Button
style="@style/Tile"
android:id="@+id/button2"
android:onClick="b2"/>

<Button
style="@style/Tile"
android:id="@+id/button3"
android:onClick="b3"/>

<Button
style="@style/Tile"
android:id="@+id/button4"
android:onClick="b4"/>


And i want to trigger a method if user does not interact with them within 20 seconds, and also if user interact the method will be different.
can you please help me solve this problem, or guide me where should i look for solution.

Answer

Define a Runnable. This will get executed if the Button will not get clicked in 20 seconds:

final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // do something
        aMethod();
    }
};

Create a Handler and post the Runnable with a delay of 20 seconds:

final Handler handler = new Handler();
handler.postDelayed(runnable, 20000);

If the Button gets clicked, call removeCallbacks() on the Handler, which will effectively remove the pending Runnable from the Handler's message queue:

Button button = (Button) findViewById(R.id.button1);

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        handler.removeCallbacks(runnable);

        // do your Button stuff
    }
});
Comments