【发布时间】:2015-12-17 01:57:08
【问题描述】:
在 API 19 之前,比updatePeriodMillis 30 分钟的最短时间更快更新 Widget 的首选方法是使用 AlarmManager 和 BroadcastReceiver 在设置时使用的指定间隔后接收 Intent启动警报管理器。
目前,使用以下代码更新 Widget,但从 Android 5.1 开始,使用 .setRepeating() 重复间隔小于 60000ms 将自动将其间隔设置为至少 60000ms。
在小部件 onEnabled() 中设置闹钟:
AlarmManager am= (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 3 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ 3000, 1000 , pi);
然后在AlarmManagerBroadcastReceiver的onReceive()中:
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");
//Acquire the lock
wl.acquire();
/*
* ......
* Update Widgets RemoteViews
*/
wl.release();
setRepeating() 的文档中写道:
注意:从 API 19 开始,所有重复警报都是不准确的。如果您的应用程序需要精确的交付时间,那么它必须使用一次性精确警报,并如上所述重新安排每次。 targetSdkVersion 早于 API 19 的旧版应用程序将继续将其所有警报(包括重复警报)视为准确。
它现在还声明:
安排重复警报。注意:对于计时操作(滴答声、超时等),使用
Handler会更容易、更高效
那么您将如何使用 Handler 更新 Widgets Remoteviews?当设备进入睡眠状态以节省电量时,如何让它停止?
还有其他更新小部件的建议方法吗?
【问题讨论】:
-
我的回答有问题吗?你试过了吗?
标签: android android-widget android-handler