Томас Петр Томас Петр - 4 years ago 139
Android Question

How to keep application awake in background

I program an application, which is connected to bluetooth device and used in a car (in the background) and navigation (or something else) in the foreground.

But on android 7+ (maybe also 6), application go to sleep after some time. When I'm trying to take picture from camera the "sleep mode" is immediately and my app is sleeping now (no bluetooth connection, no notifications) - just dead app.

I must go to recent apps -> click on my app and this make the "wake up". Bluetooth is now connecting to device again.

But I can't still check if the app is sleeping or not. So, how to keep app awake also in background?

I read some about WakeLock, but it looks like it's not working, cause app still sleeping. BUút maybe I'm using it wrong.

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wk = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyWakeLock");

and onDestroy



Answer Source

From Android API 23 onward, Google has introduced Doze mode and App Standby in order to conserve battery power. When a device enters doze mode or an app enters App Standby, all tasks done by an app is deferred. We had an issue with an Alarm which was firing because of the same. If you rad upon docs, you will find that using a Wake Lock is not gonna help either.

Doze restrictions The following restrictions apply to your apps while in Doze:

Network access is suspended.

The system ignores wake locks.

Standard AlarmManager alarms (including setExact() and setWindow()) are deferred to the next maintenance window. If you need to set alarms that fire while in Doze, use setAndAllowWhileIdle() or setExactAndAllowWhileIdle(). Alarms set with setAlarmClock() continue to fire normally — the system exits Doze shortly before those alarms fire.

The system does not perform Wi-Fi scans.

The system does not allow sync adapters to run. The system does not allow JobScheduler to run

So if you want to bypass all these, your app must have a process in the foreground. Once again from the same doc -

The app has a process currently in the foreground (either as an activity or foreground service, or in use by another activity or foreground service).

In your case run a service and raise it's priority to foreground.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download