Aruna Aruna - 3 months ago 8
Android Question

StartTimer() Should call after button click event completed, but it is get executed before onclick event

StartTimer() function Should call after button click event completed, but it is get executed before onclick event. ro how to stop timer before onclick event and start after onclick event.

How do I fix this?

btn1=(Button)findViewById(R.id.button);
btn2=(Button)findViewById(R.id.button2);
btn3=(Button)findViewById(R.id.button3);
timer = new Timer();

btn1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
timer.cancel();
Toast.makeText(getApplicationContext(), "Button1", Toast.LENGTH_SHORT).show();
}
});
StartTimer();

btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();
Toast.makeText(getApplicationContext(), "Button2", Toast.LENGTH_SHORT).show();
}
});
StartTimer();

btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();
Toast.makeText(getApplicationContext(), "Button3", Toast.LENGTH_SHORT).show();
}
});
}

public void StartTimer()
{
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Log.v("timer", "Timer running");
}
}, 0, 5000);

Toast.makeText(getApplicationContext(), "Timer", Toast.LENGTH_LONG).show();
}

protected void onResume() {
super.onResume();
StartTimer();
}
}

Answer

There is already built in Timer class in android. So you can do like that:

    import java.util.Timer;

    Timer timer = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.v("timer", "Timer running");
                Toast.makeText(getApplicationContext(), "TIMER HAS FINISHED", Toast.LENGTH_SHORT).show();
            }
        }, 0, 5000);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
                Toast.makeText(getApplicationContext(), "Button1", Toast.LENGTH_SHORT).show();
            }
        });

        StartTimer();

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
                Toast.makeText(getApplicationContext(), "Button2", Toast.LENGTH_SHORT).show();
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
                Toast.makeText(getApplicationContext(), "Button3", Toast.LENGTH_SHORT).show();
            }
        });

So just start timer in onCreate, and stop it when button clicked.