I'm trying to update fragment on clock time, say for example 8PM, with below logic. Unfortunately, it doesn't update the fragment. Any help/reference would be appreciated.
What I did:
registered an AlarmManager in app's Application class as below:
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent().setAction(AppConstants.INTENT_ACTION_UPDATE_DASHBOARD); alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0); // Set the alarm to start at Consulting start time Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); alarmMgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
Listens for AlarmManager in Fragment as below:
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mDashboardUpdateReceiver, new IntentFilter (AppConstants.INTENT_ACTION_UPDATE_DASHBOARD));
and performs actions if broadcast receives:
private BroadcastReceiver mDashboardUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Dashboard updating..."); updateCounters(); }
First, a
PendingIntent
does not trigger a local broadcast. You cannot useLocalBroadcastManager
here.Second, using
AlarmManager
to update a UI is rather odd. If your UI exists, you have a process running, so you could use something in-process (e.g.,ScheduledExecutorService
) rather than fussing withAlarmManager
.Third, you are not taking into account that
set(Calendar.HOUR_OF_DAY, hour)
andcalendar.set(Calendar.MINUTE, minute)
might change theCalendar
to be in the past. Imagine if you execute your first code snippet at 23:00, withhour
set to be22
andminute
set to be0
. TheCalendar
object that you create will be for today, but for 22:00 today, which was an hour before now (23:00). You need to check theCalendar
, see if it is in the past, and if so,add()
a day or otherwise adjust it to some future time.