1

I have made a background service in my project. How can I keep the background service alive?

I use the following code:

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            ambil_jam();
            return StartCommandResult.Sticky;
        }

However, it only keeps it alive when I close the app and when I try to clear the RAM the background service closed.

I also use this:

[Register("onTaskRemoved", "(Landroid/content/Intent;)V", "GetOnTaskRemoved_Landroid_content_Intent_Handler")]
public virtual void OnTaskRemoved()
{
     StartService(new Intent(this, typeof(SimpleService)));
}

However, it is never called when I close my app. Does the method onTaskRemoved() override, or do I need to call it again?

I'm using Xamarin.Android.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
neneo
  • 646
  • 1
  • 8
  • 21
  • what do you mean by "clear the RAM". Please explain exactly what you are doing. – David Wasser Aug 12 '16 at 08:34
  • sorry, i mean close the app using task manager – neneo Aug 12 '16 at 08:37
  • What version of Android are you testing on? – David Wasser Aug 12 '16 at 08:49
  • I'm using Xiaomi redmi note 2 prime, Android version 5.0.2 – neneo Aug 12 '16 at 09:14
  • Is your `Service` being automatically restarted after it is killed? Add logging to `onCreate()` in your `Service` so you can check. – David Wasser Aug 12 '16 at 09:48
  • Are you swiping the task from the list, or are you using the Settings->Applications->MyApp and then "force close"? – David Wasser Aug 12 '16 at 09:49
  • yup, i'm swiping the task from the list. I try on facebook and twitter, but the services turn on again – neneo Aug 15 '16 at 07:59
  • is your `Service` being automatically restarted? – David Wasser Aug 15 '16 at 12:55
  • no, i'm just using StartCommandResult.Sticky, do you have an example how to create Service that can automatically restarted? – neneo Aug 16 '16 at 03:44
  • 2
    There are power-saving controls on some of these phones that may be preventing your `Service` from getting restarted. Please see this question and the answer.: http://stackoverflow.com/questions/26615633/how-to-auto-restart-a-service-when-killed and let me know if this helped you. – David Wasser Aug 16 '16 at 08:10
  • 1
    Because i only have xiaomi smartphone to develop my app, then follow the instruction `Open the Security app provided by Xiaomi, Click on permissions -> Autostart, Here allow your app to auto start`. It works perfectly now!!! Thanks @DavidWasser :D – neneo Aug 16 '16 at 09:16

1 Answers1

1

There are power-saving controls on some phones that may be precenting your Service from getting restarted. Xiaomi, Huawei, LG and others have a separate setting that allows you to control this.

  • Open the Security app provided by Xiaomi
  • Click on permissions -> Autostart
  • Here allow your app to auto start
David Wasser
  • 93,459
  • 16
  • 209
  • 274