Rahul Rahul - 1 month ago 12
Android Question

How to Start Timer from One Activity and Stop from another activity?

I want to start a Timer from a class which will keep on running until i stop from it from other class. For this,
I have created class for timer and methods named startTimer and stopTimer as given below:

public class TimerTaskClass extends Application {
Timer timer = new Timer();

public static final int TIME_INTERVAL = 10000;

public void startTimer(final Context context) {

Log.d("Constants", "Timer Started");
timer.scheduleAtFixedRate(new java.util.TimerTask() {

@SuppressLint("DefaultLocale")
@Override
public void run() {

//Performing my Operations

}
}, 0, TIME_INTERVAL);

}



public void stopTimer() {
timer.cancel();
}


What i am doing is, I have two activity ClassA and ClassB

Class A{

onCreate(){
TimerTaskClass tmClass=new TimerTaskClass();
tmClass.startTimer();
}


}

Class B{

onCreate(){
TimerTaskClass tmClass=new TimerTaskClass();
tmClass.stopTimer();
}


}


But this is not stopping my timer which i have started from ClassA. How this can be done?

Answer

Maybe you could change TimerTaskClass to singleton, so in both activities you will use the same instance of TimerTaskClass, it should solve your problem.

public class TimerTaskClass 
{
    private static TimerTaskClass _instance;

    private TimerTaskClass ()
    {

    }

    public synchronized static TimerTaskClass getInstance()
    {
        if (_instance == null)
        {
            _instance = new TimerTaskClass ();
        }
        return _instance;
    }
}
Comments