如何更新时钟时间片段 [英] how to update fragment on clock time
问题描述
我正在尝试使用以下逻辑在时钟时间更新片段,例如8PM。不幸的是,它不会更新片段。任何帮助/参考将不胜感激。
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.
我做了什么:
-
在应用的应用程序类中注册了 AlarmManager :
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);
在片段中监听AlarmManager,如下所示:
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();
}
推荐答案
首先, PendingIntent
不会触发本地广播。您不能在此处使用 LocalBroadcastManager
。
First, a PendingIntent
does not trigger a local broadcast. You cannot use LocalBroadcastManager
here.
第二,使用 AlarmManager
更新UI很奇怪。如果您的UI存在,则说明您正在运行一个进程,因此可以使用某些进程内的东西(例如 ScheduledExecutorService
),而不用大惊小怪地使用 AlarmManager
。
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 with AlarmManager
.
第三,您没有考虑设置(Calendar.HOUR_OF_DAY,小时)
和 calendar.set(Calendar.MINUTE,分钟)
可能会将 Calendar
更改为过去。想象一下,如果您在23:00执行您的第一个代码段,并且 hour
设置为 22
和分钟
设置为 0
。您创建的日历
对象将用于今天,但今天将用于22:00,这是现在的一个小时(23:00)。您需要检查日历
,看看它是否是过去的,如果是,则每天检查 add()
或将其调整为将来的某个时间。
Third, you are not taking into account that set(Calendar.HOUR_OF_DAY, hour)
and calendar.set(Calendar.MINUTE, minute)
might change the Calendar
to be in the past. Imagine if you execute your first code snippet at 23:00, with hour
set to be 22
and minute
set to be 0
. The Calendar
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 the Calendar
, see if it is in the past, and if so, add()
a day or otherwise adjust it to some future time.
这篇关于如何更新时钟时间片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!