I would like to obtain the time that passes from the start of an activity until a click is executed on one of its buttons.
I guess I have to declare something in onCreate()
And then get the value that has passed since the onCreate() was executed until the called button was pressed, for example bt1
:
bt1.setOnClickListener(new AdapterView.OnClickListener() {
@Override
public void onClick( View view) {
//Aquí se guardaría el tiempo...
siguienteActividad();
But how?
You could get the milliseconds at each place, and compare
before the onCreate() you declare two variables of type Date
then inside onCreate() you get the current date and time as follows
and in your click event you get the current time and date again, and subtract the milliseconds that each Date returns, we would obtain when milliseconds passed, divide by 1000 and we have a second, divide by 60 and we have minutes, and so you can continue dividing
You can use time in milliseconds or dates for any task.
You need three steps:
Here some examples:
With time in elapsed milliseconds:
With elapsed time using a date object:
The idea you have is correct, as you comment you can obtain the value in milliseconds of the initial time when the Activity starts, this inside
onCreate()
and when clicking the button obtain the final time.To get the elapsed time in seconds, you can do:
But it is also important to assign the correct listener to the button, in this case it must be
OnClickListener
from the view :This is a complete example in which I add comments as an explanation:
If you want to reset the time after clicking and get the elapsed time, just get the
tiempoInicial
when doing the calculation.