0

I have a question about a problem that I’m facing in the last weeks. I´m trying to implement an Android Service.

Because I need my app to do work 24/7. I´m implementing my service like this.

AndroidManifest.xml:

<service android:enabled="true" android:name=".SimpService"/>

SimpService.cs:

using System;
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.OS;
using System.Threading;
using Android.Util;
using Xamarin.Forms;

namespace App5
{
[Service]
public class SimpService : Service
{
static readonly string TAG = "X:" + typeof(SimpService).Name;
static readonly int TimerWait = 4000;
Timer _timer;
PowerManager powerManager;
PowerManager.WakeLock wakeLock;

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        try
        {
            Log.Debug(TAG, "OnStartCommand called at {2}, flags={0}, startid={1}", flags, startId, DateTime.UtcNow);
            _timer = new Timer(o => {
                Log.Debug(TAG, "Hello from SimpleService. {0}", DateTime.UtcNow);
            }, null, 0, TimerWait);

            Notification.Builder builder = new Notification.Builder(this)
                .SetContentTitle("App Service")
                .SetContentText("App Running!")
                .SetSmallIcon(Resource.Drawable.notifications);

            Notification note = builder.Build();

            powerManager = (PowerManager)GetSystemService(PowerService);
            wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial, "MyWakelockTag");

            wakeLock.Acquire();

            //Here i call functions that i what to run

            StartForeground((int)NotificationFlags.ForegroundService, note);
            return StartCommandResult.RedeliverIntent;
        }
        catch (Exception ex )
        {
            Console.WriteLine("Erro na função OnStartCommand: {0}", ex.Message);
            StopService(new Intent(this, typeof(SimpService)));
            return StartCommandResult.RedeliverIntent;
        }
    }

    public override void OnTaskRemoved(Intent rootIntent)
    {
        try
        {
        Intent restartService = new Intent(ApplicationContext, this.Class);
        restartService.SetPackage(PackageName);
        PendingIntent restartServicePI = PendingIntent.GetService(ApplicationContext, 1, restartService, PendingIntentFlags.OneShot);
        //Restart the service once it has been killed android
        AlarmManager alarmService = (AlarmManager)ApplicationContext.GetSystemService(AlarmService);
        alarmService.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 100, restartServicePI);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            //Write Error on File as Log
        }
    }


    public override void OnCreate()
    {
        base.OnCreate();
    }

    public override IBinder OnBind(Intent intent)
    {
        return null;
    }

    public override void OnDestroy()
    {
        try
        {
            base.OnDestroy();

            _timer.Dispose();
            _timer = null;

            if (TAG != null)
            {
                Log.Debug(TAG, "SimpleService destroyed at {0}.", DateTime.UtcNow);
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            //Write Error on File as Log
        }  
    }  


}
}

The problem is that my service start working, but after some hours its stops, and I can’t understand why.

I already implemented try-catch to get if occurs some errors on service running. But don’t get anything.

I would like to know if my service, is correctly implemented, or if I’m missing something on the implementation.

My main objective is to main a service that run 24/7 without stop unless smartphone run out of batery.

Any help is welcome.

Thanks.

integer
  • 221
  • 4
  • 13
  • 1
    Possible duplicate of [Service vs IntentService](http://stackoverflow.com/questions/15524280/service-vs-intentservice) – SushiHangover Jan 23 '17 at 16:03

1 Answers1

0

Service should not be used for long running tasks. You should use IntentService instead.

Anas EL HAJJAJI
  • 1,048
  • 2
  • 10
  • 22
  • But for what i read IntentService stop when task complete. And i dont what the service to stop. Because i have operations to do, from time to time. If Intent Service is the solution for an 24/7 running service, can you give an example of how i implement an intent for running 24/7? Thanks. – integer Jan 23 '17 at 16:46
  • for example a while(condition) { } will make it run indifenitely, you can stop it if condition changed. – Anas EL HAJJAJI Jan 23 '17 at 16:51
  • Another question, but the Android OS not kill this “Intent Service”, as it is doing with my actual “Service”? For example, if the service is running for too long, or consuming too much CPU? Because the problem that I’m facing is that after some hours, the Android OS stop the service, for a reason not understating (at least, I already have not understand why it is stopping). – integer Jan 23 '17 at 22:11
  • @Integer If the Android OS is killing the service process there will be a Logcat entry... Might be an OOM condition or your service is throwing an unhandled managed exception, native exception, etc... Monitoring logcat **and** implementing a crash reporting system (like HockeyApp) would be my first areas to focus on. – SushiHangover Jan 23 '17 at 23:03
  • I´m using the HockeyApp and I think I found, some of the bugs that where causing problems and they are now corrected, thanks @SushiHangover. I have read some topics (http://stackoverflow.com/a/12881417/7055665) in stack overflow, that says the opposite of what @ Anas EL HAJJAJI, saying that for what I’m trying to do (run a service 24/7, I should use a normal service, that I start, and stop whenever I thinks e appropriated). – integer Jan 24 '17 at 13:36
  • I´m starting to become a little confused, because I read in some places to use a normal, service and in others to user an IntentService. Can someone tell if a normal Service can run 24/7, or if I need to implement something different. – integer Jan 24 '17 at 13:37