Kevin van Mierlo
Kevin van Mierlo

Reputation: 9814

Wear OS Alarm app: launch alarm Activity from AlarmManager or BroadcastReceiver

I'm trying to create a standalone alarm app for my watch (Pixel Watch 2). It was going smooth until I needed to show the screen (Activity) when the alarm goes off to show a snooze button. I tried many different things like:

So I'm not sure what to try anymore. I've tried all variations with different Intent Flags and nothing happens. Only thing that does work is if I use a PendingIntent with Activity and keep the app open, the Activity will launch (same happens when starting from the BroadcastReceiver.

I'm not sure what kind of code helps, so I'll show passing the PendingIntent with Activity:

<!-- Part of AndroidManifest -->
        <activity
            android:name=".activities.AlarmActivity"
            android:exported="false"
            android:showWhenLocked="true"
            android:taskAffinity=""
            android:noHistory="true"
            android:excludeFromRecents="true"
            android:launchMode="singleTop"
            android:turnScreenOn="true" />
val Context.alarmManager: AlarmManager
    get() = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager

fun setAlarm(context: Context, millis: Long) {
        val alarmManager = context.alarmManager
        if(!alarmManager.canScheduleExactAlarms()) {
            return
        }
        val alarmActivity = Intent(context, AlarmActivity::class.java).also {
            it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        context.alarmManager.setAlarmClock(
            AlarmManager.AlarmClockInfo(
                millis,
                PendingIntent.getActivity(context, 1, Intent(context, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
            ),
            PendingIntent.getActivity(context, 2, alarmActivity, PendingIntent.FLAG_IMMUTABLE)
        )
    }
class AlarmActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        logd("on create alarm activity")

        setTheme(android.R.style.Theme_DeviceDefault)

        setContent {
            MyTheme {
                Box(modifier = Modifier.fillMaxSize()) {
                    Text("Alarm!!")
                }
            }
        }

        setTurnScreenOn(true)
    }
}

I'm out of ideas, so if someone has an idea to point me in the right direction, that would be much appreciated.

Upvotes: 1

Views: 147

Answers (0)

Related Questions