Created
November 30, 2020 16:50
-
-
Save saamerm/5c7ce0fa781fe7f953f15a71b9a1cc88 to your computer and use it in GitHub Desktop.
Backgrounding service sample for Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Timers; | |
using Android.App; | |
using Android.Content; | |
using Android.OS; | |
namespace SampleBackgroundServices.Droid | |
{ | |
public class TimeTrackingService : Service | |
{ | |
// Declare a timer which will fire every minute | |
private Timer TimeTracker = new Timer(5000); | |
public EventHandler<ElapsedEventArgs> TimerElapsed; | |
public override IBinder OnBind(Intent intent) | |
{ | |
return new TimeTrackingServiceBinder(this); | |
} | |
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) | |
{ | |
TimeTracker.Elapsed += TimeTracker_Elapsed; | |
TimeTracker.Start(); | |
return StartCommandResult.Sticky; | |
} | |
public override void OnDestroy() | |
{ | |
TimeTracker.Elapsed -= TimeTracker_Elapsed; | |
base.OnDestroy(); | |
} | |
private void TimeTracker_Elapsed(object sender, ElapsedEventArgs e) | |
{ | |
TimerElapsed(this, e); | |
} | |
} | |
public class TimeTrackingServiceBinder : Binder | |
{ | |
public TimeTrackingService Service { get; private set; } | |
public TimeTrackingServiceBinder(TimeTrackingService pService) | |
{ | |
this.Service = pService; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment