我正在制作一个使用 BroadcastReceiver 和 WakefulServiceIntent 的应用程序,每 10 分钟在我的应用程序中调用一个方法。问题是,有时它会调用它,有时它不会。我需要每 10 分钟调用一次此方法,即使应用程序正在后台运行或屏幕已关闭。我当前的代码如下。我不应该使用 AlarmManager 来启动计时器吗?我听说 AlarmManager 不准确,但不准确到它甚至不响的地方?
AlarmManager 启动代码:
Intent intent = new Intent(getContext(), UpdateReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis() + ((2 * 60) * 1000)), ((10 * 60) * 1000), pendingIntent);
广播接收器类:
public class UpdateReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, UpdateService.class);
startWakefulService(context, service);
}
}
WakefulIntentService 类:
public class UpdateService extends IntentService {
public UpdateService() {
super("UpdateService");
}
@Override
protected void onHandleIntent(Intent intent) {
System.out.println("updated automatically");
OverviewFragment.refresh(getApplicationContext());
UpdateReceiver.completeWakefulIntent(intent);
}
}