I´m trying to have a service that executes some code in a Handler at every second. While the phone is connected to the PC everythings running fine. However as soon as I start the service while not connected to the PC and I lock the phone, the periodic task just stops executing and executes all posted events when the app is opened again.
I´ve tried adding a PARTIAL_WAKE_LOCK
in the onCreate
of the Service but it doesn´t help at all.
Service.java
private PowerManager.Wakelock mWakeLock;
private Handler mHandler;
private Timer mTimer;
@Override
public void onCreate() {
super.onCreate();
Notification notification = createNotification();
startForeground(1, notification);
// create and acquire the WakeLock
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "APP:LockName");
mWakeLock.acquire();
// create Handler for periodic code execution
HandlerThread thread = new HandlerThread("PeriodicThread", THREAD_PRIORITY_BACKGROUND);
thread.start();
Looper looper = thread.getLooper();
mHandler = new Handler(looper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new PeriodicTask(), 0, 1000);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel();
mWakeLock.release();
}
private class PeriodicTask extends TimerTask {
@Override
public void run() {
mHandler.post(() -> { // periodic task here});
}
}
I would expect the service to execute normally when the screen is locked, since the whole execution is protected by the PARTIAL_WAKE_LOCK
.
Or are WakeLocks Thread-specific and I need to acquire a lock for the newly created Thread?
Many Thanks for your help
Edit 1:
I´ve tried adding the permission REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
to the app and even then the behavior is phone dependent. On a Samsung phone it works now as intended and the task is executed each second. on Huawei phone there´s no change and the periodic task is only executed when the app is opened again.
Is there a way to at least secure the same behaviour on different phones?