Hi! I'm trying to periodically check with a web service if a new item has been added to a database. If there's a new item a listview that the user sees should be updated.
I'm using PCL and I have accomplish it creating a new Task with a timer inside. But this only works if the app is open. I want to do the same when the app is closed so the user gets a notification when a new item is added remotely.
I've been doing some research and I found andoid services, the info said that the service will continue, regardless of the app state, until you tell it to stop. But i haven't found many examples in how to implement it.
Here's the code that I had that works only when the app is opened:
Task.Run(() =>
{
Device.StartTimer(TimeSpan.FromSeconds(secs), checkUpdates);
});
bool checkUpdates()
{
if (isOnline)
{
var lastUp= Application.Current.Properties["lastUpdate"] as string;
//returns true if a new item is added
if (service.newItem(DateTime.Parse(lastUp)))
{
var itm = service.getNewItem(DateTime.Parse(lastUp));
Device.BeginInvokeOnMainThread(() =>
{
notification.ShowNotification(itm.Title, 1000);
listView.Insert(0, itm);
}
});
}
App.Current.Properties["lastUpdate"] = DateTime.Now.ToString();
}
return true;
}
I'm trying to do the same with an Android service using dependency services, here's what I've got so far:
public interface IService
{
void Start();
}
[Service]
public class DependentService : Service, IService
{
public void Start()
{
var intent = new Intent(Android.App.Application.Context, typeof(DependentService));
Android.App.Application.Context.StartService(intent);
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
// From shared code or in your PCL
return StartCommandResult.NotSticky;
}
}
The problem is that I don't know how to implement the code that I had in the timer to the service, can someone please help?