Home > Software engineering >  Starting activity at specific hour using alarm manager in Jetpack Compose
Starting activity at specific hour using alarm manager in Jetpack Compose

Time:09-05

I'm developing an App using Jetpack Compose, and I want a specific page to open at a specific hour even when the app is not open.

I'm currently using this code:

val alarmManager =
        context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

    val calendar: Calendar = getInstance().apply {
        timeInMillis = System.currentTimeMillis()
        set(Calendar.HOUR_OF_DAY, 3)
        set(Calendar.MINUTE, 54)
    }

    alarmManager.setRepeating(
        AlarmManager.RTC_WAKEUP,
        calendar.timeInMillis,
        1000 * 5,
        PendingIntent.getActivity(context, 0,
            Intent(context, SecondActivity::class.java), FLAG_IMMUTABLE)
    )

It opens the page at around 3:54 but if the app is not open or is in the background the page is not shown.

It is only shown a few seconds after I open the app again or select it from the background.

CodePudding user response:

This is the expected outcome as clearly explained in the Android Docs.

The suggested solution is to show notifications.

Android 10 (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background. These restrictions help minimize interruptions for the user and keep the user more in control of what's shown on their screen.

Note: For the purposes of starting activities, an app running a foreground service is still considered to be "in the background".

Exceptions to the restriction

  • The app has an activity in the back stack of an existing task on the Recents screen.

Note: When such an app attempts to start a new activity, the system places that activity on top of the app's existing task but doesn't navigate away from the currently-visible task. When the user later returns to the app's task, the system starts the new activity instead of the activity that had previously been on top of the app's task.

  • Related