0

I'm a newbie for xamarin.Android can anybudy guide me for doing the " Run a Method/Task Even My App is Close " in Xamarin.Android for Notification purpose

GASRON
  • 3
  • 1
  • 4
  • Maybe you could try to use the `Foreground Sevice`,refer to https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/#background-execution-limits-in-android-80 – Leo Zhu Jan 02 '20 at 08:51
  • Could you please add more explanation of what you’re trying to get done – Saamer Jan 05 '20 at 07:00
  • i want run a method for notification the user for every 10 even my app is close.tell me how run a method/task/function even my app is close? and thk – GASRON Jan 06 '20 at 14:03

1 Answers1

0

You could use Foreground Sevice by start a foregroud notification

and you could refer to the similar case,refer to the codes

1.Create a Service MyService.cs :

[Service(Enabled = true)]
public class MyService : Service
{
    private Handler handler;
    private Action runnable;
    private bool isStarted;
    private int DELAY_BETWEEN_LOG_MESSAGES = 5000;
    private int NOTIFICATION_SERVICE_ID = 1001;
    private int NOTIFICATION_AlARM_ID = 1002;
    private string NOTIFICATION_CHANNEL_ID = "1003";
    private string NOTIFICATION_CHANNEL_NAME = "MyChannel";
    public override void OnCreate()
    {
        base.OnCreate();

        handler = new Handler();

        //here is what you want to do always, i just want to push a notification every 5 seconds here
        runnable = new Action(() =>
        {
           if (isStarted)
            {
                DispatchNotificationThatAlarmIsGenerated("I'm running");
                handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
            }
        });
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        if (isStarted)
        {
            // service is already started
        }
        else
        {
            CreateNotificationChannel();
            DispatchNotificationThatServiceIsRunning();

            handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
            isStarted = true;
        }
        return StartCommandResult.Sticky;
    }

    public override void OnTaskRemoved(Intent rootIntent)
    {
        //base.OnTaskRemoved(rootIntent);
    }

    public override IBinder OnBind(Intent intent)
    {
        // Return null because this is a pure started service. A hybrid service would return a binder that would
        // allow access to the GetFormattedStamp() method.
        return null;
    }

    public override void OnDestroy()
    {
        // Stop the handler.
        handler.RemoveCallbacks(runnable);

        // Remove the notification from the status bar.
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.Cancel(NOTIFICATION_SERVICE_ID);

        isStarted = false;
        base.OnDestroy();
    }

    private void CreateNotificationChannel()
    {
        //Notification Channel
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationImportance.Max);
        notificationChannel.EnableLights(true);
        notificationChannel.EnableVibration(true);
        notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });


        NotificationManager notificationManager = (NotificationManager)this.GetSystemService(Context.NotificationService);
        notificationManager.CreateNotificationChannel(notificationChannel);
    }

    //start a foreground notification to keep alive 
    private void DispatchNotificationThatServiceIsRunning()
    {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
               .SetDefaults((int)NotificationDefaults.All)
               .SetSmallIcon(Resource.Drawable.Icon)
               .SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
               .SetSound(null)
               .SetChannelId(NOTIFICATION_CHANNEL_ID)
               .SetPriority(NotificationCompat.PriorityDefault)
               .SetAutoCancel(false)
               .SetContentTitle("Mobile")
               .SetContentText("My service started")
               .SetOngoing(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
        StartForeground(NOTIFICATION_SERVICE_ID, builder.Build());
    }

    //every 5 seconds push a notificaition
    private void DispatchNotificationThatAlarmIsGenerated(string message)
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

        Notification.Builder notificationBuilder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
            .SetSmallIcon(Resource.Drawable.Icon)
            .SetContentTitle("Alarm")
            .SetContentText(message)
            .SetAutoCancel(true)
            .SetContentIntent(pendingIntent);

        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.Notify(NOTIFICATION_AlARM_ID, notificationBuilder.Build());
    }
}

2.in your activity :

protected override void OnResume()
  {
      base.OnResume();
      StartMyRequestService();
  }
public void StartMyRequestService()
  {
      var serviceToStart = new Intent(this, typeof(MyService));
      StartService(serviceToStart);
  }

update:

   public override void OnCreate()
    {
        base.OnCreate();

        handler = new Handler();

        //here is what you want to do always, i just want to push a notification every 5 seconds here
        runnable = new Action(() =>
        {
           if (isStarted)
            {
                DispatchNotificationThatAlarmIsGenerated("I'm running");
                handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
            }
        });
    }
Leo Zhu
  • 15,726
  • 1
  • 7
  • 23
  • When runing the [sample project](https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/applicationfundamentals-servicesamples-foregroundservicedemo/) it show Java.Lang.SecurityException what i do now ? – GASRON Jan 09 '20 at 13:47
  • you should add the permission which the exception said – Leo Zhu Jan 09 '20 at 13:49
  • can u say which permission pls – GASRON Jan 09 '20 at 13:54
  • i run the same sample project .can u make me a simple sample project for Foreground service? and put me a link – GASRON Jan 09 '20 at 13:58
  • i will update tomorrow,now i‘m not in front of computer – Leo Zhu Jan 09 '20 at 14:01
  • @GASRON you could refer above,it's a simple sample,i just want to every 5 seconds to push a notification – Leo Zhu Jan 10 '20 at 02:49
  • "DispatchNotificationThatServiceIsRunning()" notification can't be cancel.How to display the "DispatchNotificationThatAlarmIsGenerated" notification without displaying "DispatchNotificationThatServiceIsRunning()" notification? – GASRON Jan 10 '20 at 14:56
  • i have one question i use StopForeground(true); ,StopSelf and StopService to stop the service but it keep on runing notification for every 5 second.how i permanently stop it? can u suggest answer pls – GASRON Jan 16 '20 at 08:54
  • @GASRON if you want the "DispatchNotificationThatServiceIsRunning",you could create a channel for it and then set it to `IMPORTANCE_LOW` ,and if you want to stop the notification,you could add a judgment see update above – Leo Zhu Jan 16 '20 at 09:32
  • thk it help a lot but myservice is not working after restarting my phone what i do now? pls don't get irritate and srry for that bcz i'm newbie – GASRON Jan 16 '20 at 15:39
  • @GASRON yes,when you restart your phone,it will stop,you should start it again – Leo Zhu Jan 17 '20 at 01:13
  • how i start it automatically after restarting my phone without going to my app? – GASRON Jan 17 '20 at 05:27
  • @GASRON you could try to create a `BroadCastReceive` to catch `BOOT_COMPLETED` intent,then start the service in the `OnReceive` method ,refer to https://stackoverflow.com/questions/49403069/xamarin-android-receiver-on-boot-completed-error – Leo Zhu Jan 17 '20 at 05:37
  • thks a lot it help me and how i contact you for further question – GASRON Jan 17 '20 at 07:11
  • can you answer this [https://stackoverflow.com/questions/59802344/how-to-invoke-a-method-using-broadcast-receiver-whenever-network-internet-is-ava]Question? – GASRON Jan 18 '20 at 16:08
  • i try connectivitychange in mainfest but it is not working so i ask question here[https://stackoverflow.com/questions/59810630/how-to-invoke-a-method-even-my-app-is-close-using-broadcast-receiver-whenever-ne] can u answer for it – GASRON Jan 19 '20 at 13:51