我正在构建一个当前作为独立应用程序运行的应用程序,该应用程序使用 AsyncTask 轮询服务。我想将轮询移至启动时运行并可能通知用户更改的 Android 服务。曲线球是我需要在活动(以及即将成为服务)之间共享这些数据,这样我就不会在持久存储和内存存储之间来回消耗电池。
有没有办法创建在后台运行的服务,使用 AlarmManager 每半分钟轮询一次,与用户界面共享(通过常量)数据,用户界面可以通过单击服务创建的通知或通过启动器本身启动?
现在这是我已经走了多远:
这是服务:
public class PollService extends Service {
private final IBinder binder = new PollBinder();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedData.update();
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class PollBinder extends Binder {
PollService getService() {
return PollService.this;
}
}
}
这将触发服务...
public class PollScheduleReceiver extends RoboBroadcastReceiver {
private static final int POLL_FREQ_SEC = 30;
@Override
protected void handleReceive(Context context, Intent intent) {
Intent schedulerIntent = new Intent(context, PollStartReceiver.class);
PendingIntent pendingSchedulerIntent = PendingIntent.getBroadcast(context, 0, schedulerIntent, PendingIntent.FLAG_CANCEL_CURRENT);
calendar.add(Calendar.SECOND, POLL_FREQ_SEC);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), POLL_FREQ_SEC * 1000, pendingSchedulerIntent);
}
}
这将在启动时触发触发器:
public class PollStartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent pollService = new Intent(context, PollService.class);
context.startService(pollService);
}
}