Subash
Subash

Reputation: 147

Background Service in Xamarin Forms

I have a background service in android is implemented as :

 [Service]
public class PeriodicService : Service
{
    public override IBinder OnBind(Intent intent)
    {
        return null;
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        base.OnStartCommand(intent, flags, startId);

        // From shared code or in your PCL]
        Task.Run(() => {
            MessagingCenter.Send<string>(this.Class.Name, "SendNoti");
        });

        return StartCommandResult.Sticky;
    }

}

In MainActivity Class :

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        UserDialogs.Init(() => (Activity)Forms.Context);
        LoadApplication(new App());

        StartService(new Intent(this, typeof(PeriodicService)));
    }
}

In Xamarin Forms in My login page :

 public LoginPage()
    {
        InitializeComponent();

        int i = 0;
        MessagingCenter.Subscribe<string>(this, "SendNoti", (e) =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                i++;

                CrossLocalNotifications.Current.Show("Some Text", "This is notification!");                        

                }
            });
        });

    }

The main problem here is my Periodic service is not sending any message except for the first time. The notification is shown only once! Please help.

Upvotes: 0

Views: 3505

Answers (1)

SushiHangover
SushiHangover

Reputation: 74209

Create an IntentService to send your notifications:

[Service(Label = "NotificationIntentService")]
public class NotificationIntentService : IntentService
{
    protected override void OnHandleIntent(Intent intent)
    {
        var notification = new Notification.Builder(this)
                           .SetSmallIcon(Android.Resource.Drawable.IcDialogInfo)
                           .SetContentTitle("StackOverflow")
                           .SetContentText("Some text.......")
                           .Build();
        ((NotificationManager)GetSystemService(NotificationService)).Notify((new Random()).Next(), notification);
    }
}

Then use the AlarmManager to setup a repeating alarm using a pending intent that "calls" your IntentService:

using (var manager = (Android.App.AlarmManager)GetSystemService(AlarmService))
{
    // Send a Notification in ~60 seconds and then every ~90 seconds after that....
    var alarmIntent = new Intent(this, typeof(NotificationIntentService));
    var pendingIntent = PendingIntent.GetService(this, 0, alarmIntent, PendingIntentFlags.CancelCurrent);
    manager.SetInexactRepeating(AlarmType.RtcWakeup, 1000 * 60, 1000 * 90, pendingIntent);
}

Upvotes: 2

Related Questions