0
我正在构建一个当前作为使用AsyncTask轮询服务的独立应用程序运行的应用程序。我想将轮询移动到开始运行的Android服务,并可能会通知用户有关更改。曲线球是我需要跨活动(即将成为服务)共享这些数据的,因此我不会在持久存储和内存存储之间来回使用电池。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);
}
}