AlarmManager for calling a service in Android P: startForegroundService
Asked Answered
F

1

2

I am using AlarmManager as below and its working fine for Android O and below.

AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i=new Intent(context, PeriodicChecksService.class);
        PendingIntent pi=PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + firstGoOffTime, frequencyInMS , pi);

But in Android P am getting the below error in Logcat:

Background start not allowed: service Intent { flg=0x4 cmp=com.app.appname/.PeriodicChecksService (has extras) } to com.app.recorder/.PeriodicChecksService from pid=-1 uid=10321 pkg=com.app.appname startFg?=false

I believe its because we have to use startForegroundService while starting a service. How do we do that in AlarmManager?

Foretell answered 13/12, 2018 at 9:40 Comment(0)
K
1

After Android O, you can use PendingIntent.getForegroundService.

Retrieve a PendingIntent that will start a foreground service, like calling Context.startForegroundService(). The start arguments given to the service will come from the extras of the Intent.

Komsa answered 13/12, 2018 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.