Global Timer in android

后端 未结 5 859
日久生厌
日久生厌 2021-01-21 13:40

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 T         


        
5条回答
  •  天涯浪人
    2021-01-21 14:00

    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);
    }
    

提交回复
热议问题