androidandroid-workmanagerandroid-timer

Android Application code stop when phone screen is locked


I've coded the app that check the conditions for every minute in background and if it true then it will send notification/vibrate.

It works fine, but only when my phone is active (means the screen is not locked).

I've tried many solutions like using Services, JobSchedule, WorkManager (current) but they seem not work. The behavior of WorkManager code is like this:

(While the phone screen is locked)

(Turn on the screen)

Mass notifications appears, like the task is ran while locked, but only show when unlock the screen

Can anyone help me on this? I'm using OnePlus 9 Pro for testing

Code Snippet

public class MyService extends Worker {
    Timer myTimer;
    TimerTask doThis;
    private DBHelper mydb;

    public MyService(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

   @Override
    public Result doWork() {
        StrictMode.setThreadPolicy(new Builder().permitAll().build());
        mydb = new DBHelper(getApplicationContext());
        // Let it continue running until it is stopped.
        myTimer = new Timer();
        int delay = 0;   // delay for 0 sec.
        int period = 1000*60;  // repeat every 60 sec.
        doThis = new TimerTask() {
            public void run() {
             //Some task
             if (true) {
                                    notify("aaaa");
                                    Log.e("OK", "Match!");
                        }

                    ...

        myTimer.schedule(doThis, delay, period);
        return Result.success();
    }

Solution

  • The issue with your app is not the process but rather the android system itself.

    You need to implement something called the DOZE MODE. Such that the process/ application is not killed off when the phone is locked Google Docs On Doze Mode There is a permission you would need to implement called the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS.