Reputation: 4253
In my mainactivity I start service.
In service I have a pendingintent to show notifications to users every 15 minutes:
my AlarmReceiver class:
public class AlarmReceiver extends Service {
public void onCreate() {
super.onCreate();
showNotify();
AlarmManager alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intentn = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intentn, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= 23) {
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 900), pendingIntent);
}
else {
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 900), pendingIntent);
}
So I'd like to repeate the alarm in my service to show notifications every 15 min. The problem is it is never repeating. I try flag_update_current, and others but I think the problem isn't the flags... Any ideas?
Upvotes: 0
Views: 245
Reputation: 1505
You can Use WorkManager
instead of service.Initial workmanager
in the Application
class.
override fun onCreate() {
super.onCreate()
WorkManager.initialize(
this,
Configuration.Builder()
.setWorkerFactory(appComponent.factoryAppWorker())
.build()
)
initWorkManager()
}
private fun initWorkManager(){
Log.d("MainRepository","initWorkManager")
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val notificationRequest =
PeriodicWorkRequestBuilder<PullNotificationWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build()
WorkManager.getInstance(this)
.enqueueUniquePeriodicWork(PULL_PERIODIC_NOTIFICATION_WORK_NAME,ExistingPeriodicWorkPolicy.REPLACE,notificationRequest)
}
And workmanager
class should like this:
class PullNotificationWorker @AssistedInject constructor(
@Assisted private val appContext: Context,
@Assisted private val params: WorkerParameters,
private val repository: MainRepository
) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result = coroutineScope{
Log.d(TAG,"doWork")
try {
createNotification(it)
}
Result.success()
} catch (throwable: Throwable) {
Log.d(TAG,"work faile=${throwable.message}")
Result.failure()
}
}
}
For more information read android developer docs.workmanager
Upvotes: 1
Reputation: 1
Have you tried changing PendingIntent.getService
to PendingIntent.getBroadcast
instead? It works for me.
Here is the code that I'm using:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pIntent = PendingIntent.getBroadcast(code, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.setExact(AlarmManager.RTC, time, pIntent);
//Do something
}
}
Upvotes: 0