Global Timer in android

2020-04-15 11:07发布

问题:

I want to make a timer which will be shown on every activity of my application.

I know how to make a timer on an activity below is my code

public class Timer extends Activity implements OnClickListener {
    public TextView mTextField;
    private Button btnstart;

    public String formatTime(long millis) { 
        String output = "00:00"; 
        long seconds = millis / 1000; 
        long minutes = seconds / 60; 

        seconds = seconds % 60; 
        minutes = minutes % 60; 

        String secondsD = String.valueOf(seconds); 
        String minutesD = String.valueOf(minutes); 

        if (seconds < 10) 
            secondsD = "0" + seconds; 
        if (minutes < 10) 
            minutesD = "0" + minutes; 

        output = minutesD + " : " + secondsD; 
        return output; 
    } 
    public CountDownTimer Counter1;

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 

        //Declare Start/Stop button 
        btnstart = (Button)findViewById(R.id.btnThread1); 
        btnstart.setOnClickListener(this);
        //Button btnstop = (Button)findViewById(R.id.button02); 
        //Button btnpass = (Button)findViewById(R.id.button03);

        //Declare Text fields to show time left 
        final TextView mCounter1TextField=(TextView)findViewById(R.id.txtThread1); 
        final TextView mCounter2TextField = (TextView)findViewById(R.id.txtThread2); 
        //final TextView mCounter3TextField=(TextView)findViewById(R.id.textView03); 



        //Counter 1 
        Counter1 = new CountDownTimer(120000 , 1000) { 
            public void onTick(long millisUntilFinished) { 
                mCounter1TextField.setText("Seconds left: " + formatTime(millisUntilFinished)); 
            } 

            public void onFinish() { 
                mCounter1TextField.setText("Finished!"); 
                // Counter1.start();
            } 
        }; 
    }

    @Override
    public void onClick(View v) {
        if(v == btnstart)
        {
            Counter1.start();
        }

    }
}

I want to know how to make it global??

回答1:

You can have a singleton class holding your CountDownTimer

// This is not a real singleton, Google to get a proper Java implementation
public class TimerSingleton {

  // Should not be public, you should of course encapsulate access to that timer.
  // static keyword says that one timer object is shared by all instance of TimerSingleton 
  public static CountDownTimer timer = new CountDownTimer();
}

// Access to the timer from an activity:
TimerSingleton.timer.start();

Second option is to have your timer as a member of a custom Application class: Use Application class for global variables

Third option : make a local service that starts the timer when started.

Keep in mind that in case of options 1 and 2, if the OS decides to kill you app, the timer will vanish (i.e. when the activity is re-created, the CountDownTimer object will be resetted).



回答2:

Create a Singleton! http://en.wikipedia.org/wiki/Singleton_pattern

singleton guarantee that there will be only one object of some kind and makes it easy for any other object to access it.



回答3:

If you want to show it one every activity of your application, then I suggest you to use Fragments. All you need to do is to create a Fragment with your Timer class that will appear every time, another Fragment with other content you want to show, and manipulate the lifecycle of the second Fragment only.



回答4:

I have solved my problem by making a timer in one activity and calling its protected function in my other activity.

This is the startTimer function to start the timer:

private void startTimer(){ 
    if (mTimer == null) { 
        mTimer = new Timer(); 
    } 
    if (mTimerTask == null) { 
        mTimerTask = new TimerTask() { 
            @Override 
            public void run() { 
                Log.i(TAG, "count: "+String.valueOf(count)); 
                sendMessage(UPDATE_TEXTVIEW); 

                do { 
                    try { 
                        Log.i(TAG, "sleep(1000)..."); 
                        Thread.sleep(1000); 
                    } catch (InterruptedException e) { 
                    }    
                } while (isPause);  
                count ++;   
            } 
        }; 
    } 
    if(mTimer != null && mTimerTask != null ) 
        mTimer.schedule(mTimerTask, delay, period); 
} 

and this is the public function which can be used by any other activity:

public String valueOfTimer()
{
    return String.valueOf(count);
}

and this is how I am getting the value on other activity:

private void updateTime()
{
    TimerActivity tm  = new TimerActivity();

    String time = tm.valueOfTimer();
    t2.setText(time);
    System.out.println("Time::"+time);
}


回答5:

make a singleton class and register listener in your ui.

 mTimerCustom = CountdownTimer.getInstance();
 mTimerCustom.registerListener(this);
 mTimerCustom.start();

in CountDownTimer class

 public static CountdownTimer getInstance()
    {
        return INSTANCE;
    }

 public synchronized void start() {

        Calendar cal=Calendar.getInstance();
        int seconds=cal.get(Calendar.SECOND);
       start=60-seconds;
        //Toast.makeText(mParentActivity,""+seconds,Toast.LENGTH_LONG).show();
        if (D) Log.d(TAG, "start");
        switch (state) {
            case STOPPED:
                count = start;
            case PAUSED:
                timer = new Timer(TAG);
                timer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        if (count > 0) {
                            count--;
                            Log.d(TAG, "Tick: " + count);
                            for (TimerListener listener : listeners) {
                                listener.timerUpdate(count);
                            }
                        }
                        else stop();
                    }
                }, 0, DELAY);
                state = COUNTING;
                if (D) Log.d(TAG, "state: counting");
                break;
            case COUNTING:
                break;
            default:
                throw new IllegalStateException(state.toString());
        }
    }


标签: android timer