Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Countdown timer to show same time in all Activities

I have created a fragment, that is visible on the top of 4 Activities, I have created a Countdown Timer in my Fragment, Its working fine.

The problems is that, on each Activity timer refreshes, and starts from 00:03:00, I have created timer for 3 Minutes, I want it show the same time in all activities, and not refresh itself on each activity.

This is my code.

public class myCartFragment extends Fragment {

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view =  inflater.inflate(R.layout.cart_header_fragment, container, false);
        tvTimer= (TextView) view.findViewById(R.id.tvTimer);
        CountDownTimer countDownTimer= new CounterClass(180000, 1000);
        countDownTimer.start();    
        }


    public  class CounterClass extends CountDownTimer{
        @Override
        public void onTick(long millisUntilFinished) {
            long millis= millisUntilFinished;
            String hms= String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
                    );    
            tvTimer.setText(hms);
        }
}

I am using this fragment in my activities by using following code in my Layout XML file

    <fragment
        android:id="@+id/calendarFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="fragments.myCartFragment"
        tools:layout="@layout/header_fragment" />
</LinearLayout>
like image 642
dev90 Avatar asked Aug 16 '16 12:08

dev90


People also ask

What is countdown interval?

countDownInterval : The interval along the way to receive onTick(long) callbacks.


2 Answers

Use the single instance of your CounterClass throughout all the Activities/Fragments

Use static method to initialize getInstance and retrieve values getFormatedTime().

public class CounterClass  extends CountDownTimer{

private static String hms;
private static CounterClass instance;

private CounterClass(long millisInFuture, long countDownInterval){
    super(millisInFuture,countDownInterval);
}

public static CounterClass  initInstance(long millisInFuture, long countDownInterval){
    if(instance==null){
        instance =  new CounterClass(millisInFuture,countDownInterval);
    }
    return instance;
}

public static CounterClass  getInstance() throws Exception{
    if(instance==null){
        throw new Exception("Parameters not initialized. Initiate with initInstance");
    }else{
        return instance;
    }
}

public static String getFormatedTime(){
    return hms;
}
@Override
public void onTick(long l) {

    long millis= l;
    hms= String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
            TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
    );
}
@Override
public void onFinish() {

}
}

I have modified the code.

Inorder to initiate the CounterClass, do the following.

CounterClass counterClass = CounterClass.initInstance(180000, 1000);
counterClass.start();

For accessing the previous value

try {
      CounterClass counterClass = CounterClass.getInstance();
      Log.i("TAG 222", counterClass.getFormatedTime());
     } catch (Exception e) {
       e.printStackTrace();
       // counter class is not initiated , access initInstance
     }

As android.os.CountDownTimer does not have default constructor, this is the way we can achieve your requirement

like image 89
Sreehari Avatar answered Oct 13 '22 03:10

Sreehari


Maybe you want to place the timer in your activity and use multiple fragments. You can add/replace fragments within the activity as you want.

Each fragment can receive the timer's ticks via a listener (Observer Pattern).

In your activity define:

public interface onTimerTick{
void timerTick(long millisUntilFinished);
}

and keep a reference to the fragment(s) that implement the interface:

List<onTimerTick> listeners=new ArrayList<>();
listeners.add(new Fragment1());

in the timer's onTick:

public  class CounterClass extends CountDownTimer{
        @Override
        public void onTick(long millisUntilFinished) {
           for(onTimerTick fragment:listeners){
fragment.timerTick(millisUntilFinished);
}
        }
}

then each fragment:

public class Fragment1 extends Fragment implements onTimerTick{
@Override
void timerTick(long millisUntilFinished){
//display remaining time
}

Another approach is to send a broadcast when the timer ticks, then each fragment having a broadcast receiver will receive the timer value.

like image 25
Mina Wissa Avatar answered Oct 13 '22 03:10

Mina Wissa