1

I have app that needs to fetch data from Room Database ( Wrapper for SQLite basically ) every minute to do some checks that data.

I have made implementation with Handler which triggers this async call every minute. Handler is registered on mainThread but when task is called, it dispatches a new thread to run this task in background.

My problem is that this operation does not need to occur when Application is not in foreground. Ideally the Handler would fire task when app gets back to foreground, and after that task is finished, it should schedule next call in 1 minute.

But when I leave my app by clicking on Home button, open other apps, I still see my app making logs about this operation being done.

My issue is that I am afraid this will, if let to run for 6 or 7 hours, leave a battery impact on users phone. There are no wake locks made in App.

EDIT: There are 3 activities that use this class, and this (BackcgroundExecutor) is inner class of singleton. If I connect it to lifecycle of one, I would have to make it work depending on lifecycle of all 3 to be proper.

How would you fix this issue?

private class BackgroundExecutor implements Runnable {
    @Override
    public void run() {
        Thread temp = new Thread(new Runnable() {
            @Override
            public void run() {
                long time = Calendar.getInstance().getTimeInMillis();
                Log.d("DB", time + " inside of Run method");
                evaluateTasks();
                evaluateComplexTasks();
                long nextTime = nextMinute();
                handler.postAtTime(new BackgroundExecutor(), nextTime);
            }
        });
        temp.start();
    }

    void evaluateTasks() {
        // Grab tasks
        Task[] tasks = dao.primaryDAO().loadTasksForCheck();
        LinkedList<Task> tasksToUpdate = new LinkedList<>();
        // Evaluate if any of them got data changed
        for (Task t: tasks) {
            if (t.checkForFieldUpdate()) {
                tasksToUpdate.add(t);
            }
        }
        // Re-save those that have
        if (tasksToUpdate.size() > 0) {
            Task[] temp = new Task[tasksToUpdate.size()];
            tasksToUpdate.toArray(temp);
            dao.primaryDAO().insertTask(temp);
        }
    }

    void evaluateComplexTasks() {
        // Grabs Complex Tasks
        ComplexTasks[] complexTasks = dao.primaryDAO().loadComplexTasksForCheck();
        LinkedList<ComplexTasks> tasksToUpdate = new LinkedList<>();
        // Evaluate if all tasks are completed
        for (ComplexTasks t: complexTasks) {
            if (t.checkForTaskStatusUpdate()) {
                tasksToUpdate.add(t);
            }
        }
        // Re-save those tasks;
        if (tasksToUpdate.size() > 0) {
            dao.primaryDAO().insertComplexTask((ComplexTasks[]) tasksToUpdate.toArray());
        }

    }
}

0 Answers0