Home > Software design >  Is it possible to run java code when activity is not launched?
Is it possible to run java code when activity is not launched?

Time:11-22

I am working on an alarm java application. I want to run Alarm(); function when the systems clock arrives to the targetTime. But I want to do these even the application is not open. So somehow I want to run it in androids background.

My code :

void AlarmCheck (DateTimeAlarm currentTime, DateTimeAlarm targetTime)
{
    if(!targetTime.alarmed && currentTime.day == targetTime &&
        currentTime.hour == targetTime.hour && currentTime.minute >= targetTime.minute)
    {
        targetTime.alarmed = true;
        Alarm();
    }
}

And this is the class for the DateTimeAlarm :

public class DateTimeAlarm
{
    public int day;
    public int hour;
    public int minute;
    public bool alarmed = false;

    public DateTimeAlarm(int day, int hour, int minute)
    {
        this.day = day;
        this.hour = hour;
        this.minute= minute;
    }
}

I have no idea where to put this code PLEASE HELP ME.

I am new to java so please explain easily. thank you for any suggesions.

CodePudding user response:

This is the time when you start learning about services. If you want long running operations in background, you must make a service to do that for you. I leave the link to the official site for you. https://developer.android.com/guide/components/services

CodePudding user response:

It has become increasingly difficult to do background tasks in Android using Services, use a WorkManager instead: https://developer.android.com/topic/libraries/architecture/workmanager

  • Related