How to show an alert dialog on all activities?

Hi,

I have a timer in one of my activities that shows an alert dialog every minute. This works fine on the activity it is created on but what I need is it to continue showing every minute despite what activity I have open.

Any ideas how I'd do that?

Heres my timer and alert dialog.

private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
okbuttonpressed = false;
Activity activity = this;
Console.WriteLine ("Alert");
Android.App.AlertDialog.Builder builder = new AlertDialog.Builder (activity);
RunOnUiThread(() =>
alertDialog = builder.Create ());
RunOnUiThread(() =>
alertDialog.SetTitle ("Welfare Alert"));
RunOnUiThread(() =>
alertDialog.SetMessage ("Alert triggered"));
RunOnUiThread(() =>
alertDialog.SetButton("OK", (s, ev) =>
{
okbuttonpressed = true;
}));
RunOnUiThread(() =>
alertDialog.Show ());
}

Answers

  • LoriLalondeLoriLalonde CAInsider, University, Developer Group Leader ✭✭✭
    edited September 2015

    Create a BaseActivity class which contains the implementation you want every activity to adopt, then ensure all your activities extend your BaseActivity.

    Also you can refactor your RunOnUiThread calls as follows:

    RunOnUiThread(() => 
                    {
                        alertDialog = builder.Create();
                        alertDialog.SetTitle("Welfare Alert");
                        alertDialog.SetMessage("Alert triggered");
                        alertDialog.SetButton("OK", (s, ev) =>
                                            {
                                                okbuttonpressed = true;
                                            });
                        alertDialog.Show();
                    }
                );
    
  • hobeauhobeau USMember

    A good way to keep track of this is to create a central class to track what activity you are currently and also to run your timed thread in. Here's an example:

    `using System;
    using System.Threading.Tasks;
    using Android.App;
    using Android.Views;

    namespace XamarinAndroidForum
    {
    public static class App
    {
    // Keep track of what current activity you are on here
    public static Activity _currentActivity;
    private static Task _alertLoop;

        public static void RunAlertThread()
        {
                    // Keep track of thread to see if it's already running if it is just ignore
            if (_alertLoop == null || _alertLoop.Status != TaskStatus.Running)
            {
                                // Run as async task
                _alertLoop = Task.Run(async () =>
                {
                                        // If you want to cancel the task later you may want to put a 
                                        // variable in here to set to false
                    while (true)
                    {
                        var builder = new AlertDialog.Builder(_currentActivity);
                        builder.SetTitle("Welfare Alert");
                        builder.SetMessage("Alert Triggered");
    
                                                // Keep what runs on the UI thread to a minimum
                        _currentActivity.RunOnUiThread(() =>
                        {
                            try
                            {
                                builder.Show();
                            }
                                                    // If the current activity isn't set correctly it will throw a 
                                                        // WindowManagerBadTokenException
                            catch(WindowManagerBadTokenException ex1)
                            {
    
                            }
                            catch(Exception ex2)
                            {
    
                            }
                        });
    
                        // Wait for 1 minute (milliseconds)
                        await Task.Delay(60000);
                    }
                });
            }
        }
    }
    

    }`

    To start the thread, in your MainActivity you will need to add the following to your 'OnCreate' override method:

    App._currentActivity = this; App.RunAlertThread();

    and then add this to your override 'OnRestart' method:

    App._currentActivity = this;

    The reason for that is the OnCreate method doesn't fire if you navigate back to MainActivity with the back button. You will need to include App._currentActivity = this; in OnCreate override methods throughout your activities so that the thread knows what activity to alert on.

    Also, I would keep a minimal amount of code in your RunOnUiThread as this can bog down the UI and you want to run as much code externally from the UI thread as you can.

  • FussbotFussbot GBMember

    Thank you for your answers.

    @hobeau your example is great thanks, I have another time execute every 30 seconds that checks for the ok button clicked if not a welfare alert call and text are sent.

    How would I incorporate those into this code?

    private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
    {
    okbuttonpressed = false;
    Activity activity = this;
    Console.WriteLine ("Alert");
    Android.App.AlertDialog.Builder builder = new AlertDialog.Builder (activity);
    RunOnUiThread(() =>
    alertDialog = builder.Create ());
    RunOnUiThread(() =>
    alertDialog.SetTitle ("Welfare Alert"));
    RunOnUiThread(() =>
    alertDialog.SetMessage ("Alert triggered"));
    RunOnUiThread(() =>
    alertDialog.SetButton("OK", (s, ev) =>
    {
    okbuttonpressed = true;
    }));
    RunOnUiThread(() =>
    alertDialog.Show ());
    bTimer = new System.Timers.Timer();
    bTimer.Elapsed+=OnTimedEvent2;
    bTimer.Interval= 30000;
    bTimer.Enabled=true;
    }

        private void OnTimedEvent2(object source, System.Timers.ElapsedEventArgs e)
        {
            if (!okbuttonpressed) {
                contactInfo = DataController.emergencyDetails;
                var uri = Android.Net.Uri.Parse ("tel:" + contactInfo["phone"].ToString() + "");
                var intent = new Intent (Intent.ActionCall, uri);
                intent.SetPackage("com.android.phone");
                StartActivity (intent);
                SendMessage();
            }
        }
    
        protected void SendMessage() {
    
            String phoneNo = contactInfo["phone"].ToString();
            String message = "Emergency, I'm here: https://maps.google.com/maps?q=loc:" + DataController.currentlat + "," + DataController.currentlng + "&z=17";
    
            try {
                SmsManager smsManager = SmsManager.Default;
                smsManager.SendTextMessage(phoneNo, null, message, null, null);
                Console.WriteLine("Message Sent");
            } catch (Exception e) {
                Console.WriteLine ("Message Failed");
        }
        }
    
Sign In or Register to comment.