Forum Xamarin Xamarin.Android

App crashes after Sticky service is restarted


I have simple service for working with local notifications - which works fine until user force closes it. After that, service should restart when Android has available resources, but when that happens, I get two dialogs stating that App has crashed and by look into app manager I can see that service didn't start again. The service looks like this:

    public class NotificationService:Service
    public Intent intent;
    public PendingIntent pi;
    public AlarmManager am;
    public override Android.OS.IBinder OnBind (Intent intent)
        return null;

    [Obsolete ("deprecated")]
    public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)
        SetAlarms (DateTime.Now.AddSeconds(10));
        AlarmReceiver receiver = new AlarmReceiver ();
        return StartCommandResult.Sticky;

    public void SetAlarms (DateTime? dateTime){
        intent = new Intent (Forms.Context,typeof(AlarmReceiver));
        intent.SetAction ("show_notification");
        pi = PendingIntent.GetBroadcast(Forms.Context,0, intent,0);
        am = (AlarmManager)Forms.Context.GetSystemService(Context.AlarmService);
        am.Set (AlarmType.RtcWakeup, (long)(Java.Lang.JavaSystem.CurrentTimeMillis () + (dateTime.Value.ToUniversalTime () - DateTime.Now.ToUniversalTime ()).TotalMilliseconds), pi);

    public override void OnDestroy ()
        am.Cancel (pi);
        am.Dispose ();
        intent.Dispose ();
        pi.Dispose ();
        base.OnDestroy ();

Oh and also - I start it manually inside MainActivity's OnCreate using this code:

Intent ServiceIntent = new Intent(Forms.Context,typeof(NotificationService));
StartService (ServiceIntent);


  • luismatoslunaluismatosluna USMember ✭✭

    It's a bit late but you have found the solution to your problem?

  • AlanClarkAlanClark USMember ✭✭✭

    @LuisMts Given the age of this thread, if you're having a similar issue I would recommend creating your own thread on the topic stating what you're having issues with any any information you feel would be relevant.

Sign In or Register to comment.