I think something like this should work. The AsyncTask gets the current event name and next event start time from the database. When it found those, the current event name is set, and a runnable is posted, and executed when the next event starts. At that point you obtain that event name again and set it, and post a new delayed runnable. This way, the current event name is set when the fragment is created, or when it starts while the user has the fragment is open.
Note that you do not want to use the AlarmManager for this. From the documentation:
The Alarm Manager is intended for cases where you want to have your
application code run at a specific time, even if your application is
not currently running. For normal timing operations (ticks, timeouts,
etc) it is easier and much more efficient to use Handler.
Also note that I did not test this code thoroughly, so there might be some issues when the activity gets killed etc. This example seems to work though, as it shows a Toast message every 10 seconds.
public class MyFragment extends Fragment implements Runnable {
TextView currentEventTextView;
Handler handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
}
@Override
public void onStart() {
super.onStart();
new GetEventTask().execute();
}
@Override
public void onStop() {
handler.removeCallbacks(this);
super.onStop();
}
@Override
public void run() {
// next event is starting, so obtain it
new GetEventTask().execute();
}
private class GetEventTask extends AsyncTask<Void, Void, Event>{
@Override
protected Event doInBackground(Void... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// TODO get current name and next start time from db
Event event = new Event();
event.name = "Google I/O " + System.currentTimeMillis();
event.nextStartTime = System.currentTimeMillis() + 10000;
return event;
}
@Override
protected void onPostExecute(Event event) {
currentEventTextView.setText(event.name);
handler.postDelayed(MyFragment.this, event.nextStartTime - System.currentTimeMillis());
}
}
private class Event {
public String name;
public long nextStartTime;
}
}