我有一个需要频繁轮询数据的应用程序。我有一个带有TimerTask
实现的应用服务逻辑,但后来我被@Commonsware 转移到了WakefulIntentService。
现在我的问题是我有多个活动屏幕来响应服务发出的广播意图。我如何确保对 scheduleAlarms 的调用只会被调用一次(或者我不必为此烦恼?)。实际的问题是 scheduleAlarms 的代码放置在一个超类的 onCreate 上,如果不是所有的活动都从该超类扩展,因此会导致安排多个警报。
我有一个需要频繁轮询数据的应用程序。我有一个带有TimerTask
实现的应用服务逻辑,但后来我被@Commonsware 转移到了WakefulIntentService。
现在我的问题是我有多个活动屏幕来响应服务发出的广播意图。我如何确保对 scheduleAlarms 的调用只会被调用一次(或者我不必为此烦恼?)。实际的问题是 scheduleAlarms 的代码放置在一个超类的 onCreate 上,如果不是所有的活动都从该超类扩展,因此会导致安排多个警报。
我不确定你想做什么,但这就是我所做的:
在某项活动中:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 30);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30000, pendingIntent);
这会设置一个警报,该警报每 30 秒触发一次 AlarmReceiver 类。
在 AlarmReceiver 我有这个:
package com.android.example;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AlarmService.class);
WakefulIntentService.sendWakefulWork(context, i);
}
}
在 AlarmService 我有这个:
package com.android.example;
import android.content.Intent;
import com.commonsware.cwac.wakeful.WakefulIntentService;
public class AlarmService extends WakefulIntentService {
public AlarmService() {
super("AlarmService");
}
@Override
protected void doWakefulWork(Intent arg0) {
//DO WAKEFUL STUFF
}
}
我会告诉你什么:它有效!
我希望这有帮助!
我有一个需要频繁轮询数据的应用程序。我有一个带有 TimerTask 实现的应用服务逻辑,但后来我被 @Commonsware 转移到了 WakefulIntentService。
WakefulIntentService
专为我认为不频繁的间隔(最多每隔几分钟)而设计,与任何 UI 分离运行。听起来这不是您使用它的方式。
如何确保对 scheduleAlarms 的调用只会被调用一次
跟踪您何时调用它。
还是我不必为此烦恼?
这在一定程度上取决于时间表。
对于您针对特定时间的警报(例如,下周二下午 4 点),您可以盲目地重新安排它们,因为下周二下午 4 点不会改变。PendingIntent
如果您每次都使用等效的,Android 将在用新警报替换旧警报的过程中取消旧警报。
对于定期警报(每 N 分钟/小时/天),您可以盲目地重新安排它们,但需要注意一点:除非您小心避免,否则您的日程安排会略有变化。假设您希望每天响一次闹钟。在最后一次闹钟响起 12 小时后,您将闹钟重新安排为每天再次响起一次。如果您想确保闹钟在另外 12 小时后仍然响起(以遵守您原来的时间表),您需要知道这是必需的,并将setRepeating()
呼叫中的初始事件设置为正确的时间。