Declare your variable:
long lastTimeRecorded;
Then in onCreate get a start time:
lastTimeRecorded = System.currentTimeMillis();
Then when you update the time call this function from the activity:
public void updateTimer(){
long elapsedTime = System.currentTimeMillis() - lastRecordedTime;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putLong("elapsedTime", elapsedTime);
}
If you want it to repeat at certain intervals:
private final int interval = 1000; // in millis
private Handler handler = new Handler();
private Runnable runnable = new Runnable(){
public void run() {
updateTimer();
}
};
...
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);
From samuel, here
How to set a timer in android