Monday, August 6, 2012

Android Tracking Time - Part 2

Continuing from a previous post, I've now updated my app to track how long I've taken to return from one activity (started from my main activity).
Here's what I did:
Create variables to hold onto the times when messages are sent and returned.

public class MyFirstActivity extends Activity {
public static long time_msg_sent = 0;
public static long time_msg_returned = 0;
public static long time_diff = 0;
// rest of code like onCreate(), etc ...
}
Just before the second activity is started, set one variable with the current time.

public void sendMessage(View view) {
// do code to prepare Intent ...

time_msg_sent = System.currentTimeMillis();
startActivity(intent);
}
Add an onResume method, which is called when the first activity returns from the second activity. In this function, I added logic to calculate the elapsed time. The check for 0 and the reset back to 0 is needed because onResume is called during other points of the activity life cycle.

public void onResume() {
if ( time_msg_sent != 0 ) {
time_msg_returned = System.currentTimeMillis();
time_diff_s = (time_msg_returned - time_msg_sent) / 1000;
time_msg_sent = 0;
}
super.onResume();
}

No comments:

Post a Comment