0

I have written an app that should be running continually event if device goes to sleep mode.I have tried many things like services (with startForground also) , alarm manager and persistant="true", but when device go to sleep (by user or by device) , my app is terminated.and even PowerManager does not work too.

There is an option in device setting that is 'Keep running after screen off' (in huawei device : setting > app > my app options > battery > Keep running after screen off). So when this option is active , the app is running for ever.I want implement something like this in my app programitically.

I saw some apps that implemented this , but I dont know how. So how can I do that?

AlphaQ
  • 656
  • 8
  • 18
m n
  • 223
  • 1
  • 7
  • 19

3 Answers3

1

Use ForgroundService.
If you check your device applications with an app manager, you can see that some of them using a sevice that is always running. even if you stop them, some of them start working again.
see more about services behavior in android developer.
and search for "keeping a service alive".

Seyyed
  • 1,526
  • 3
  • 20
  • 30
1

On some devices (Huawei, Xiaomi, LG) there is a special setting that contains a list of apps that are allowed to run in the background. It sounds like you are talking about trying to accomplish the same thing. This cannot be done on those devices. On those devices, unless your app is added to the list of apps that are allowed to run in the background ("Protected Apps" on Huawei), the Android framework will not restart your app if it is shutdown. There is no way for you to programatically add your app to this list, and there is no way for you to work around this feature.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • there is some applications on my device that stay active till user close them.in their monifest there is no service.but i dont know how they implemented this feature. – m n Jan 03 '17 at 17:06
  • How do you know that they are active? Define "active"? Are these apps in the list of "protected apps" on the phone? – David Wasser Jan 03 '17 at 17:38
  • first , they stay on last activity (not main).second they do something and send notification when their process done. – m n Jan 03 '17 at 21:08
  • I'm sorry, I cannot understand your last comment. – David Wasser Jan 04 '17 at 08:49
1

Certain apps need to keep the screen turned on, such as games or movie apps. The best way to do this is to use the FLAG_KEEP_SCREEN_ON in your activity (and only in an activity, never in a service or other app component).

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);