I am trying to run a service to check the network status. I need to check this every hour, even if the app has been force closed form the recent app tray. I have created the service and it works on load and runs once. Not sure how to run it every hour and after its been closed.
Service
using System;
using System.IO;
using Android.App;
using Android.Content;
using Android.Net;
using Android.OS;
using Android.Widget;
namespace example.Services
{
[Service(Label = "NetworkService")]
[IntentFilter(new String[] { "com.example.NetworkService" })]
public class NetworkService : Service
{
IBinder binder;
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
// start your service logic here
string filename = "network.txt";
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, filename);
if(!File.Exists(filePath))
File.Create(filePath);
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo;
bool isOnline = networkInfo.IsConnected;
if(isOnline)
{
File.WriteAllText(filePath, "Connected");
}
else
{
File.WriteAllText(filePath, "Not Connected");
}
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
binder = new NetworkServiceBinder(this);
return binder;
}
}
public class NetworkServiceBinder : Binder
{
readonly NetworkService service;
public NetworkServiceBinder(NetworkService service)
{
this.service = service;
}
public NetworkService GetNetworkService()
{
return service;
}
}
}
Manifest
<service android:enabled="true" android:name="com.example.NetworkService" />
MainActivity
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
namespace whitesrecycling.Activities
{
[Activity(Label = "HomeActivity")]
public class HomeActivity : Activity
{
protected override void OnStart()
{
base.OnStart();
StartService(new Intent(this, typeof(Services.NotifcationService)));
StartService(new Intent(this, typeof(Services.NetworkService)));
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Home);
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetActionBar(toolbar);
ActionBar.Title = "Example";
}
}
}