Creating a never ending background service in Android ?

jackrajjackraj USMember ✭✭
edited January 2018 in Xamarin.Android

I have tried android services following way to create android services working fine.but I need creating never-ending background services in android services. So how can I run this service in background and always.

https://developer.xamarin.com/guides/android/application_fundamentals/services/creating-a-service/

Creating never-ending background services

In above task is done in java in the following URL

https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android

In c# xamarin android above task, I can't able to do

I need task in c# please let us know

I have posted my code and question at the following URL

https://forums.xamarin.com/discussion/106540/how-to-run-background-service-even-the-app-is-closed-aim-services-is-always-run#latest

https://forums.xamarin.com/discussion/105882/created-android-services-but-i-call-my-own-method-in-android-services-every-day-4-clock-pm-only#latest

Posts

  • jackrajjackraj USMember ✭✭

    I have created services fine.

    My question is below

    1.An app is locked state only services are working in the background suppose is the app is not locked services are not working in background mentioned on the screen below.
    2.Reboot the devices that time services not working.
    3.Attached AndroidManifest.xml

    I have pasted full code below

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>

















    Sevices
    service android:name=".SensorService" android:label="@string/ApplicationName" android:exported="true"

    Receiver
    receiver android:name=".SensorRestarterBroadcastReceiver"
    android:enabled="true"
    android:exported="true"
    android:permission="[email protected]

    Main activity.cs

    using Android.App;
    using Android.Widget;
    using Android.OS;
    using Android.Content;
    using StartServices.Servicesclass;
    using System;
    using Android.Util;

    namespace StartServices
    {
    [Activity(Label = "StartServices", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
    Intent mServiceIntent;
    private SensorService mSensorService;
    protected override void OnCreate(Bundle bundle)
    {
    base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);           
            mServiceIntent = new Intent(this, typeof(SensorService));
            if (!isMyServiceRunning(Java.Lang.Class.FromType(typeof(SensorService))))
            {
                StartService(mServiceIntent);
            }
        }
        private bool isMyServiceRunning(Java.Lang.Class serviceClass)
        {
            ActivityManager manager = (ActivityManager)GetSystemService(Context.ActivityService);
            // foreach (RunningServiceInfo service in manager.GetRunningServices(int.MaxValue))
            foreach (var item in manager.GetRunningServices(int.MaxValue))
            {
                if (serviceClass.Name.Equals(item.Service.ClassName))
                {
                    return true;
                }
            }
            return false;
        }
        protected override void OnDestroy()
        {
            try
            {
                PellucidLog.Logfile.WriteEventLog("Class:MainActivity", "Method:OnDestroy", 0, "Called", System.Diagnostics.TraceEventType.Information);
                base.OnDestroy();
                StopService(mServiceIntent);
                Log.Info("MAINACT", "onDestroy!");               
    
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    

    }

    SensorService.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using Android.App;
    using Android.Content;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.Util;
    using Java.Util;
    using StartServices.Recevierclass;
    using Android.Telephony;

    namespace StartServices.Servicesclass
    {
    [Service(Exported = true)]
    public class SensorService : Service
    {

        public int counter = 0;
        public SensorService(Context applicationContext)
        {
            //_context=applicationContext;
            PellucidLog.Logfile.WriteEventLog("Class:SensorService", "Method:SensorService", 0, "ApplicationContext Called", System.Diagnostics.TraceEventType.Information);
            Log.Info("HERE", "here I am!");
        }
        public SensorService()
        {            
            PellucidLog.Logfile.WriteEventLog("Class:SensorService", "Method:SensorService", 0, "Constructor Called", System.Diagnostics.TraceEventType.Information);
            Log.Info("HERE", "here I am contructor!");
        }
        public override void OnCreate()
        {
            base.OnCreate();
            PellucidLog.Logfile.WriteEventLog("Class:SensorService", "Method:OnCreate", 0, "Called", System.Diagnostics.TraceEventType.Information);
            Log.Info("HERE", "Oncreate method SensorService");
            //Toast.MakeText(this, "Oncreate method SimpleStartedService", ToastLength.Long).Show();
        }
        public override IBinder OnBind(Intent intent)
        {           
               return null;
        }
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            PellucidLog.Logfile.WriteEventLog("Class:SensorService", "Method:OnStartCommand", 0, "Called", System.Diagnostics.TraceEventType.Information);
            startTimer();
            return StartCommandResult.Sticky;
        }
        private Timer timer;
        //private TimerTask timerTask;
        private SampleOne one;
        long oldTime = 0;
        public void startTimer()
        {
            //set a new Timer
            timer = new Timer();
            //initialize the TimerTask's job
            initializeTimerTask();
            //schedule the timer, to wake up every 1 second
            timer.Schedule(one, 1000, 1000); //
        }     
        public void initializeTimerTask()
        {
             one = new SampleOne();
             one.Run();
        }       
    
        public override void OnDestroy()
        {
            try
            {
                PellucidLog.Logfile.WriteEventLog("Class:SensorService", "Method:OnDestroy", 0, "Called", System.Diagnostics.TraceEventType.Information);
                Intent ll24 = new Intent(this, typeof(SensorRestarterBroadcastReceiver));               
                SendBroadcast(ll24);
                stoptimertask();
                base.OnDestroy();          
    
            }
            catch(Exception ex)
            {
                PellucidLog.Logfile.WriteEventLog("Class:SensorService", "Method:OnDestroy", 0, "Error : " + ex.Message, System.Diagnostics.TraceEventType.Error);
            }
        }
        public void stoptimertask()
        {
            try
            {
                //stop the timer, if it's not already null
                if (timer != null)
                {
                    timer.Cancel();
                    timer = null;
                }
            }
            catch (Exception ex)
            {
                PellucidLog.Logfile.WriteEventLog("Class:SensorService", "Method:stoptimertask", 0, "Error: " + ex.Message, System.Diagnostics.TraceEventType.Error);
            }
        }
    }
    public class SampleOne : TimerTask
    {
        public int counter = 0;
        PendingIntent sentPI;
        String SENT = "SMS_SENT";
        public override void Run()
        {
            try
            {
                Log.Info("in timer", "in timer ++++  " + (counter++));
                PellucidLog.Logfile.WriteEventLog("Class:SampleOne", "Method:Run", 0, "in timer ++++ : " + (counter++), System.Diagnostics.TraceEventType.Information);                
            }
            catch(Exception ex)
            {
                PellucidLog.Logfile.WriteEventLog("Class:SampleOne", "Method:Run", 0, "error in timer ++++ : " + ex.Message , System.Diagnostics.TraceEventType.Error);
            }
        }
    }   
    

    }

    SensorRestarterBroadcast.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using Android.App;
    using Android.Content;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using StartServices.Servicesclass;
    using Android.Util;

    namespace StartServices.Recevierclass
    {
    [BroadcastReceiver(Enabled = true)]
    [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
    public class SensorRestarterBroadcastReceiver : BroadcastReceiver
    {
    public override void OnReceive(Context context, Intent intent)
    {
    //Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();

            if (intent.Action == Intent.ActionBootCompleted)
            {
                PellucidLog.Logfile.WriteEventLog("Class:SensorRestarterBroadcastReceiver", "Method:OnReceive", 0, "ActionBootCompleted Called", System.Diagnostics.TraceEventType.Information);
                context.StartService(new Intent(context, typeof(SensorService)));
            }
            else
            {
                Log.Info("Received intent!", "Received");
                PellucidLog.Logfile.WriteEventLog("Class:SensorRestarterBroadcastReceiver", "Method:OnReceive", 0, "Else Called", System.Diagnostics.TraceEventType.Information);
                context.StartService(new Intent(context, typeof(SensorService)));
            }
        }
    }    
    

    }

    Logfile.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using Android.App;
    using Android.Content;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using System.IO;

    namespace PellucidLog
    {
    public static class Logfile
    {
    public static void WriteEventLog(string sClassName, string sFunctionName, int iErrorCode, string sErrorMessage, System.Diagnostics.TraceEventType eletLogType)
    {
    LogEvent(sClassName + " " + sFunctionName + " " + sErrorMessage, eletLogType);
    }
    public static void LogEvent(String Message, System.Diagnostics.TraceEventType type)
    {
    try
    {
    LogToFile(DateTime.Now.ToString("hh:mm:ss") + " : " + type.ToString() + ": " + Message + System.Environment.NewLine);
    }
    catch (Exception ex)
    {
    LogToFile(DateTime.Now.ToString("hh:mm:ss") + " : " + type.ToString() + ": " + ex.Message + System.Environment.NewLine);
    }
    finally
    {
    }
    }
    private readonly static object _syncklock = new object();

        public static void LogToFile(string msg)
        {
            lock (_syncklock)
            {
                try
                {
                    // if (Convert.ToBoolean(LogDisplay))
                    {
                        var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
                        Java.IO.File Download = new Java.IO.File(path);
                        if (!Download.Exists() && !Download.IsDirectory)
                        {
                            Download.Mkdir();
                        }
    
                        string directroy = System.IO.Path.Combine(path, "Pellucid");
                        Java.IO.File Pellucid = new Java.IO.File(directroy);
                        if (!Pellucid.Exists() && !Pellucid.IsDirectory)
                        {
                            Pellucid.Mkdir();
                        }
    
                        string _Filename = Path.Combine(directroy, "ServicesMobility.log");
                        if (!File.Exists(_Filename))
                        {
                            FileStream CreateFileStream = new FileStream(_Filename, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
                            CreateFileStream.Close();
                            CreateFileStream = null;
                        }
                        int _ConfigFileSizeRange = 20000;//Convert.ToInt32(WebConfigurationManager.AppSettings["FileSize"].ToString());
                        FileInfo _LogFileInfo = new FileInfo(_Filename);
                        int _LogFileLength = Convert.ToInt32(_LogFileInfo.Length.ToString());
                        if (_LogFileLength > _ConfigFileSizeRange)
                        {
                            //code commented by rajkumar palanisamy for Oct-24-2017 does create folder
                            //string destinationFileName = Path.Combine(directroy + "\\LogEntries\\" + DateTime.Now.ToString("MM.dd.yy"), DateTime.Now.ToString("hh.mm.ss") + ".txt");                           
    
                            string destinationFileName = Path.Combine(directroy, "LogEntries");// + DateTime.Now.ToString("MM.dd.yy"), DateTime.Now.ToString("hh.mm.ss") + ".txt");                            
                            Java.IO.File PellucidDestination = new Java.IO.File(destinationFileName);
                            if (!PellucidDestination.Exists() && !PellucidDestination.IsDirectory)
                            {
                                PellucidDestination.Mkdir();
                            }
                            string destinationDate = Path.Combine(destinationFileName, DateTime.Now.ToString("MM.dd.yy"));
                            Java.IO.File PellucidDatetime = new Java.IO.File(destinationDate);
    
                            if (!PellucidDatetime.Exists() && !PellucidDatetime.IsDirectory)
                            {
                                PellucidDatetime.Mkdir();
                            }
    
                            string destinationDatefile = Path.Combine(destinationDate, DateTime.Now.ToString("hh.mm.ss") + ".txt");
    
                            if (!Directory.Exists(Path.GetDirectoryName(destinationDatefile)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(destinationDatefile));
                            }
                            File.Copy(_Filename, destinationDatefile);
                            File.WriteAllText(_Filename, "");
                        }
                        File.AppendAllText(_Filename, msg);
                    }
                }
                catch (Exception ex)
                {
                    LogToFile(DateTime.Now.ToString("hh:mm:ss") + " : " + "LogToFile method" + ": " + ex.Message + System.Environment.NewLine);
                }
            }
        }
    }
    

    }




Sign In or Register to comment.