简体   繁体   中英

OnCreate called twice when using CountDownTimer in Android

I am trying to implement a view with a text view counting down a number every 600 miliseconds and dynamically displaying the number in text view.

The problem: the activity gets called as expected, but during countdown the activity gets created again and the countdown begins from the start. The OnCreate() method in my activity gets called twice although it should be called once. I know it could be triggered by a change in screen orientation and other configuration changes, but it doesn't seem to happen here.

OnCreate() in my activity:

protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.SqueezeLayout);
        countdownTextView = (TextView)FindViewById(Resource.Id.countdown_text_view);
        Timer myTimer = new Timer(18000, 600, this);
        myTimer.Start();
    }

My implementation of CountDownTimer:

class Timer : CountDownTimer
    {
        public int count = 30;
        SqueezeActivity squeezeActivity;

        public Timer(long totaltime, long interval, SqueezeActivity activity)
                                 : base(totaltime, interval)
        {
            squeezeActivity = activity;
        }

        public override void OnTick(long millisUntilFinished)
        {
            count--;
            String countStr = count.ToString();
            squeezeActivity.countdownTextView.Text = countStr;
        }

        public override void OnFinish()
        {
            squeezeActivity.StartActivity(typeof(AnotherActivity));
        }

    }

I am a beginner in Xamarin development so please be forgiving :) Thanks.

As it turned out, the method called twice was caused by a simple mistake in code logic - I was calling StartActivity twice. So it had nothing to do with the countdown timer. Thanks for the answers. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM