经常更新的小部件(比updatePeriodMillis允许更频繁)部件、频繁、updatePeriodMillis

2023-09-05 06:36:34 作者:忘记了你是谁

我希望有一个小窗口显示倒计时一辆公交车发车的用户发起的追踪。我想要更新的窗口小部件每分钟左右,从用户启动跟踪时巴士离开后(即在时间耗尽)。

I want a widget showing a countdown for a user initiated tracking of a bus departure. I want to update the widget every minute or so, from when the user initiates the tracking to when the bus has departed (i.e. the time runs out).

这个小工具需要更频繁地更新比 updatePeriodMillis 允许的话,也就是每30秒。我估计大约每分钟一次。

This widget needs to be updated more frequently than what updatePeriodMillis allows, which is every 30 seconds. I reckon about once a minute.

作为新到Android编程,我能想到的几个方法可以做到这一点,但我可能会最终会做它消耗太多的电池等的方式,所以我在寻找更有经验一些启发Android开发者。

Being new to Android programming, I can think of a few ways to do this, but I would probably end up doing it in a way that consumes way too much battery etc, so I'm looking for some insights from more experienced Android developers.

我如何开始计时?我如何可以访问我的应用程序的小部件实例运行时?等等。

How do I start the timer? How can I access the widget instance from my applications run-time? And so on.

推荐答案

我会注册一个警报,开始我的服务每1分钟和服务将更新插件用户界面

I would register an alarm to start my service every 1 minute and the service would update the widget UI

final Intent intent = new Intent(context, UpdateService.class);
final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
long interval = 1000*60;
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),interval, pending);

AlarmManager.ELAPSED_REALTIME不会wakr设备,如果它睡觉电池的寿命应该不会受到影响。

AlarmManager.ELAPSED_REALTIME will not wakr the device if it's sleeping to battery life should not be affected.

 
精彩推荐
图片推荐