Using CountDownTimer class to start ,reset a timer

Owais Ahmed 81 Reputation points
2021-03-04T18:13:14.63+00:00

I made a simple Countdowntimer app for another project , I tried my best to run this simple timer to start,pause and reset the timer.My first problem was the fact that,
Since a MainActivity cannot inherit multiple classes I had to make a new one just so I can Inherit the abstract class CountDownTimer,Secondly I do not know completely that I was able to call the CountDownTimer constructor from the abstract class because I cannot intialize an abstract class only call it form within the subclass constructor .Also , I dont understand how do I wire it up with my UI.I'm completely lost in this, Can anyone help me on this?? .I have also published the code on github

GitHub : https://github.com/owais19m/TimerApp_Test

Thanks ,

Blockquote

    using Android.App; 
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using Android.Content;
using Android.Telephony;
using Android.Provider;
using Android.Util;
using Java.Lang;
using System.Text.RegularExpressions;
using Xamarin.Essentials;
using System;
using Android;
using Android.Support.V4.Content;
using Android.Content.PM;
namespace TimerApp_Test
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        private static System.Boolean mTimerRunning;


    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);

        //------------ Views -------------

        Button ResetBtn = FindViewById<Button>(Resource.Id.ResetButton);
        Button StartBtn = FindViewById<Button>(Resource.Id.StartButton);
        TextView TimerText = FindViewById<TextView>(Resource.Id.CountdownText);

        //--------------------------------

        StartBtn.Click += (s, e) =>
        {

             if (mTimerRunning)
            {
                pauseTimer();
            }
            else
            {
                startTimer();

            }

        };

        ResetBtn.Click += (s, e) =>
        {
            resetTimer();

        };

    }

    public void startTimer()
    {
        CountDown1 Coutdwn = new CountDown1(6000,1000);
        Coutdwn.OnTick(1000);

        Coutdwn.Start();
        mTimerRunning = true;   


    }



    public void resetTimer()
    {

    }

    public void pauseTimer()
    {


    }


    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }



}


public class CountDown1 : CountDownTimer
{


    public static long Start_Time_Milliseconds = 600000;
    public static CountDownTimer mcountDownTimer;

    public static long mTimeLeftInMillis = Start_Time_Milliseconds;

    public CountDown1(long mTimeLeftInMilli, long countDownInterva) : base(mTimeLeftInMilli,countDownInterva)
    { 

    }
    public override void OnFinish() { }



    public override void OnTick(long millisUntilFinished)
    {
        mTimeLeftInMillis = millisUntilFinished;
        updateCountDownText();

    }

    public string updateCountDownText()
    {
        int minutes = (int)mTimeLeftInMillis / 1000 / 60;
        int seconds = (int)mTimeLeftInMillis / 1000 % 60;

        string timeLeftFormatted = string.Format("%02d:%02d", minutes, seconds);

        return timeLeftFormatted; 
    }

    public void Cancellation()
    {
        mcountDownTimer.Cancel();
    }
}

}

Blockquote

Developer technologies | .NET | Xamarin
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. JessieZhang-MSFT 7,716 Reputation points Microsoft External Staff
    2021-03-05T02:57:20.747+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    I made a demo based on your code and changed some code. It could work properly. You can change it according to your requirement.

    The code is:

       public class MainActivity : AppCompatActivity  
        {  
            Button StartBtn;  
            Button ResetBtn;  
            static  TextView TimerText;  
            CountDown1 Coutdwn;  
      
            protected override void OnCreate(Bundle savedInstanceState)  
            {  
                base.OnCreate(savedInstanceState);  
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);  
                // Set our view from the "main" layout resource  
                SetContentView(Resource.Layout.activity_main);  
      
                //------------ Views -------------  
                ResetBtn = FindViewById<Button>(Resource.Id.ResetButton);  
                StartBtn = FindViewById<Button>(Resource.Id.StartButton);  
                TimerText = FindViewById<TextView>(Resource.Id.CountdownText);  
      
                //--------------------------------  
                StartBtn.Click += (s, e) =>  
                {  
                    startTimer();  
                };  
                ResetBtn.Click += (s, e) =>  
                {  
                    Coutdwn.Cancel();  
                };  
            }  
      
            public void startTimer()  
            {  
                Coutdwn = new CountDown1(6000, 1000);  
                Coutdwn.Start();  
            }  
      
            public class CountDown1 : CountDownTimer  
            {  
                public static long Start_Time_Milliseconds = 600000;  
      
                public static long mTimeLeftInMillis = Start_Time_Milliseconds;  
                public CountDown1(long mTimeLeftInMilli, long countDownInterva) : base(mTimeLeftInMilli, countDownInterva)  
                {  
                }  
                public override void OnFinish() { }  
      
      
                public override void OnTick(long millisUntilFinished)  
                {  
                    mTimeLeftInMillis = millisUntilFinished;  
                    updateCountDownText();  
                }  
                public void updateCountDownText()  
                {  
                    int minutes = (int)mTimeLeftInMillis / 1000 / 60;  
                    int seconds = (int)mTimeLeftInMillis / 1000 % 60;  
                    //string timeLeftFormatted = string.Format("%02d:%02d", minutes, seconds);  
      
                    string timeLeftFormatted = minutes+" minute : " + seconds + " seconds";  
      
                    TimerText.Text = timeLeftFormatted;  
                }  
            }  
      
            public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)  
            {  
                Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
      
                base.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
            }  
        }  
    

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Owais Ahmed 81 Reputation points
    2021-03-05T17:27:27.627+00:00

    Thanks, This worked great ,just regarding this, I coded a simple notification program when my timer stops in OnFinished() method in the CountDown1 class ,I get a "Java.Lang.IllegalStateException: 'System services not available to Activities before onCreate()' " error ,is there a work around for this ?

            public NotificationCompat.Builder builder;
            MainActivity activity = new MainActivity();
            NotificationManagerCompat notificationManager;
    
            public override void OnFinish() 
            { 
                Toast.MakeText(Application.Context ,"Finished",ToastLength.Short).Show();
                 builder = new NotificationCompat.Builder(this.activity, CHANNEL_ID).SetAutoCancel(true)
               .SetContentTitle("CountDownTimer !!")
               .SetSmallIcon(Resource.Drawable.abc_ic_star_black_48dp)
               .SetContentText($" Stopped"); //  display.
    
                 notificationManager = NotificationManagerCompat.From(this.activity);   Error  //  Java.Lang.IllegalStateException: 'System services not available to Activities...
    
    
                notificationManager.Notify(NOTIFICATION_ID, builder.Build());
    
            }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.