0

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();
Ankit HTech
  • 1,863
  • 6
  • 31
  • 42

3 Answers3

3

Here is an idea. Create a separate layout for your Chronometer and <include /> it in all the layouts that require a Chronometer.

Now you can either use a Singleton pattern or SharedPreferences to 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 SharedPreference or your Singleton class 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.

  1. Ready (00:00 - Your timer is ready to run)
  2. Running (Timer is running)
  3. Paused (Timer is paused and can be resumed)
  4. Stopped (You have stopped the timer and it displays the elapsed time and the next possible state would be 1 i.e, ready.)

You would need several other parameters such as,

  1. Timer start time (System.currentTimeInMillis() minus this time gets you elapsed)
  2. Timer stop time (Used to calculate timer paused and stopped time)

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 SharedPreference in the onStop() method of your ActivityA.

Now after you start ActivityB, in the onResume() method get the start time from the SharedPreference, the System.currentTimeInMillis() minus the start time will give you the elapsed time. Next, you have to get the timer state from your SharedPreference.

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 SharedPreferences from here.

Also, you need to be familiar with the Activity lifecycle, which you can learn from here.

Ragunath Jawahar
  • 19,513
  • 22
  • 110
  • 155
2

No, you can't.

Activities have a life cycle in Android : they are created, started, display & do stuff, get stopped and destroyed. And all the views inside obey to this life cycle. Don't fight against it, that's the way Android is and it's great like that, learn this life cycle.

The views of an activity don't exist outside of it. This would have no meaning. You should read on how to pass information from one activity to another.

Also, maybe your question is : how can all my activities have the same view in their layout, each one having its own instance of the view. In that case, use the include xml keyword.

Community
  • 1
  • 1
Snicolas
  • 37,840
  • 15
  • 114
  • 173
  • I am using Chronometer for stop watch and I want to show stop watch on every activity,now I cant make it global then how to show stop watch on every activity with only one timer?? – Ankit HTech Oct 23 '12 at 05:42
  • How do you implement your timers ? Are they async tasks ? Do you use the alarm manager ? We need more code to answer this *second* question. – Snicolas Oct 23 '12 at 05:56
2

yes you can do this but not by making it global. it is little tricky.

what you have to do is: - make choronometer xml declarartion with tag in each Activity. - make access of this chronometer in base class.

Just like an example: i required header in each of activity but i wanted to do coding only at one place. so what i do is:

/**
 * Method to init Header components sets header bar title and header bar
 * buttons. This method sets onClickListener to
 */
private void initHeader() throws InvalidHeaderTitleException {
    try {
        View headerView = findViewById(R.id.header_layout);
        if (headerView != null) {
            headerTextView = (TextView) headerView
                    .findViewById(R.id.layout_header_textview_header);
            nextHeaderButton = (Button) headerView
                    .findViewById(R.id.layout_header_button_next);
            prevHeaderButton = (Button) headerView
                    .findViewById(R.id.layout_header_button_previous);
            if (headerTextView != null) {
                String title = getHeaderText();
                if (isValidString(title)) {
                    if (title.length() > IDryIceUIConstants.LENGTH_HEADER_TEXT)
                        title = title.substring(0,
                                IDryIceUIConstants.LENGTH_HEADER_TEXT)
                                + IDryIceUIConstants.SUFFIX_HEADER_TEXT;
                    headerTextView.setText(title);
                } else {
                    throw new InvalidHeaderTitleException(title);
                }
            }

            if (nextHeaderButton != null) {
                nextHeaderButton.setVisibility(getVisibility());
                nextHeaderButton.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        headerNextButtonClicked();
                    }
                });
            }

            if (prevHeaderButton != null) {
                prevHeaderButton.setVisibility(getVisibility());
                prevHeaderButton.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        headerPrevButtonClicked();
                    }
                });
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

xml declaration in each Activity xml is

<include
        android:id="@+id/header_layout"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        layout="@layout/layout_header" />
Deepika Lalra
  • 1,035
  • 1
  • 10
  • 24
  • Thanks Deepika, What about the Listener of Chronometer?? I want to read its value in each activity but that timer should be only one?? – Ankit HTech Oct 23 '12 at 06:00
  • then declare a protected method in base class to get value of chronometer. set listener in each activity when user click chronometer it will call the protected method in base class which will return value of chronometer. – Deepika Lalra Oct 23 '12 at 06:08