Service Implementation

integerinteger PTMember ✭✭

Hello,

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.

Any help is welcome.

Thanks.

Sign In or Register to comment.