foreground service never stop xamarin android

Viewed 1432

i have xamarin android application that read from clipboard and write to it. it uses foreground services if the user hit the button. the problem is when the user hit the button again the services disappear from running services but still doing it's job (editing copied text). how can i completely stop it from working?

foreground.cs:

        public override IBinder OnBind(Intent intent)
        {
            return null;
        }
    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        Clipboard.ClipboardContentChanged += async (o, e) =>
            {
                var text = await Clipboard.GetTextAsync();
                Toast.MakeText(this, text, ToastLength.Long).Show();
                if (text.Contains("@"))
                {
                    await Clipboard.SetTextAsync(text.Replace("@", ""));
                }
            };
        Notification notif = ReturnNotif();
        StartForeground(1, notif);
        return StartCommandResult.NotSticky;
    }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

        public override void OnCreate()
        {
            base.OnCreate();
        }
        public override bool StopService(Intent name)
        {
            StopForeground(true);
            StopSelf();
            return base.StopService(name);
        }

MainActivity.cs:

    if (id == Resource.Id.myService)
    {
        if (count != 1)
        {
            count = 1;
            var intent = new Intent(this, typeof(foreground));
            intent.SetAction("No");
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                StartForegroundService(intent);
            }
            else
            {
                StartService(intent);
            }
        }
        else
        {
            var intent = new Intent(this,typeof(foreground));
            StopService(intent);
            Toast.MakeText(this, "Service Stopped", ToastLength.Long).Show();
            count = 0;
        }
    }

what i am doing wrong ?

Edit : Service will completely stops if the app is removed from recently used apps.

2 Answers

In your MyForegroundService.cs. Just add StopForeground(true) in OnDestroy() method like following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace ForegroundServiceDemo
{
    [Service]
    class MyForegroundService : Service
    {
        public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;

        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            CreateNotificationChannel();
            string messageBody = "service starting";
           // / Create an Intent for the activity you want to start
           Intent resultIntent = new Intent(this,typeof(Activity1));
           // Create the TaskStackBuilder and add the intent, which inflates the back stack
           TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
           stackBuilder.AddNextIntentWithParentStack(resultIntent);
           // Get the PendingIntent containing the entire back stack
           PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
           var notification = new Notification.Builder(this, "10111")
            .SetContentIntent(resultPendingIntent)
            .SetContentTitle("Foreground")
            .SetContentText(messageBody)
            .SetSmallIcon(Resource.Drawable.main)
            .SetOngoing(true)
            .Build();
            StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
             //do you work
            return StartCommandResult.Sticky;

           
        }
        public override void OnDestroy()
        {
            base.OnDestroy();
            StopForeground(true);
        }
        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                
                return;
            }

            var channelName = Resources.GetString(Resource.String.channel_name);
            var channelDescription = GetString(Resource.String.channel_description);
            var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
            {
                Description = channelDescription
            };

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);
        }

    }
}

When you want to stop it. Just call following code.

   Android.App.Application.Context.StopService(intent);

Here is my code in the Activity.

public class MainActivity : AppCompatActivity
    {
        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);
            Button button1 = FindViewById<Button>(Resource.Id.button1);
            Button button2 = FindViewById<Button>(Resource.Id.button2);
            button2.Click += Button2_Click;
            button1.Click += Button1_Click;
        }
        Intent intent;
        private void Button2_Click(object sender, System.EventArgs e)
        {
            // stop foreground service.
            Android.App.Application.Context.StopService(intent);
        }

        private void Button1_Click(object sender, System.EventArgs e)
        {
             intent = new Intent(Android.App.Application.Context, typeof(MyForegroundService));

  // start foreground service.
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                StartForegroundService(intent);
              
            }
        }

Here is running GIF.

enter image description here

====Update====

the expected behavior is : when service stopped user can copy and paste normally without the service interference

You can use following way to achieve that.Use Clipboard.ClipboardContentChanged += Clipboard_ClipboardContentChanged; to execute the behavior, use Clipboard.ClipboardContentChanged -= Clipboard_ClipboardContentChanged; to disable the behavior in the OnDistory method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Essentials;

namespace ForegroundServiceDemo
{
    [Service]
    class MyForegroundService : Service
    {
        public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;

        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            CreateNotificationChannel();
            string messageBody = "service starting";


            Clipboard.ClipboardContentChanged += Clipboard_ClipboardContentChanged;

             // / Create an Intent for the activity you want to start
             Intent resultIntent = new Intent(this,typeof(Activity1));
           // Create the TaskStackBuilder and add the intent, which inflates the back stack
           TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
           stackBuilder.AddNextIntentWithParentStack(resultIntent);
           // Get the PendingIntent containing the entire back stack
           PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
           var notification = new Notification.Builder(this, "10111")
            .SetContentIntent(resultPendingIntent)
            .SetContentTitle("Foreground")
            .SetContentText(messageBody)
            .SetSmallIcon(Resource.Drawable.main)
            .SetOngoing(true)
            .Build();
            StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
             //do you work
            return StartCommandResult.Sticky;

           
        }

        private async void Clipboard_ClipboardContentChanged(object sender, EventArgs e)
        {
            //throw new NotImplementedException();

            var text = await Clipboard.GetTextAsync();
            Toast.MakeText(this, text, ToastLength.Long).Show();
            if (text.Contains("@"))
            {
                await Clipboard.SetTextAsync(text.Replace("@", ""));
            }
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            Clipboard.ClipboardContentChanged -= Clipboard_ClipboardContentChanged;

            StopForeground(true);
        }
        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                
                return;
            }

            var channelName = Resources.GetString(Resource.String.channel_name);
            var channelDescription = GetString(Resource.String.channel_description);
            var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
            {
                Description = channelDescription
            };

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);
        }

    }
}

Here is run GIF.

enter image description here

To prevent this issues, add a "myServiceIsRunning" bool value in the Properties dictionary when you start your foreground method like this:

Application.Current.Properties["myServiceIsRunning"] = true

With a get function or whatever you want, before start the foreground method, verify if the key "myServiceIsRunning" exist, and if it exist, how is his status:

public bool getRunningStateMyService(){
    bool myServiceIsRunningValue;
    if (Application.Current.Properties.ContainsKey("myServiceIsRunning"))
    {
        myServiceIsRunningValue = Convert.ToBoolean(Application.Current.Properties["myServiceIsRunning"]);
    }
    else
    {
        myServiceIsRunningValue = false;
    }
    return locationServiceIsRunning;
}

After you get the value, with a simple if{}/else{}, you can choose to start a new instance or not if you're service is running or not. Or, in you're case just prevent the foreground method continue to run.

Don't forget to set your value to false when you destroy the foreground method.

the Properties dictionary can store data trought closing app to. you can have more infos here: https://docs.microsoft.com/fr-fr/xamarin/xamarin-forms/app-fundamentals/application-class#Properties_Dictionary

Related