I am using
<Chronometer android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/chrono"
android:visibility="gone" />
in my one activity now my question is can I make it global for all of my activities so that I can show its value to every activity in my android app?
If yes then how to do this please give example because I am new in android??
Here is my timer code
Chronometer stopWatch;
stopWatch.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener(){
@Override
public void onChronometerTick(Chronometer arg0) {
countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000;
long min = countUp / 60;
long sec = countUp % 60;
String minStr = "";
String secStr="";
if(min < 10)
{
minStr = "0"+min;
}
else
{
minStr = ""+min;
}
if(sec<10)
{
secStr = "0"+sec;
}
else
{
secStr = ""+sec;
}
// String asText = (countUp / 60) + ":" + (countUp % 60);
String asText = minStr + ":" + secStr;
textGoesHere.setText(asText);
}
});
stopWatch.start();
Here is an idea. Create a separate layout for your
Chronometerand<include />it in all the layouts that require a Chronometer.Now you can either use a Singleton pattern or
SharedPreferencesto store the attributes such as start time, current state (Paused, Running, Stopped, Reset) of your timer. Whenever you start a new activity get the state of the timer and show it on your Timer.For instance if the current state is running then you may have to kick start a thread to update the timer or if the timer is stopped just get the start time and stop time from your
SharedPreferenceor yourSingletonclass and show it on the timer.For instance, consider the following scenario. For simplicity let’s have 2 Activities, ActivityA and ActivityB.
Now here are some of the states for your timer, yours could be different.
You would need several other parameters such as,
System.currentTimeInMillis()minus this time gets you elapsed)Let’s consider this case. You are starting a timer from ActivityA and want to retain the state on ActivityB. Here are the set of things you might want to do.
When you start your timer by any event – say click of a button, you have to save the start time in your
SharedPreference.Now you want to navigate to ActivityB, then you have to save the timer state to your
SharedPreferencein theonStop()method of your ActivityA.Now after you start
ActivityB, in theonResume()method get the start time from theSharedPreference, theSystem.currentTimeInMillis()minus the start time will give you the elapsed time. Next, you have to get the timer state from yourSharedPreference.If the state is running, then you have to start a thread to update the timer. If the timer is stopped, then it’s enough to show the time elapsed on your timer.
This is the outline of the solution. You can learn about
SharedPreferencesfrom here.Also, you need to be familiar with the Activity lifecycle, which you can learn from here.