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);
}
}