Skip to content

Instantly share code, notes, and snippets.

@TyMarc
Created July 4, 2016 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TyMarc/01a51ee76cb417f7b87beb2bf9da05fa to your computer and use it in GitHub Desktop.
Save TyMarc/01a51ee76cb417f7b87beb2bf9da05fa to your computer and use it in GitHub Desktop.
public class LongPolling {
private static final String BASE_URL = "http://serveraddress.com/";
private static final String TAG = "LongPolling";
private static LongPolling instance;
private Context context;
private PollingListener listener;
private boolean poll;
private LongPolling(final Context context) {
this.context = context;
}
public static void init(final Context context) {
if(instance == null) {
instance = new LongPolling(context);
}
}
public static LongPolling getInstance() {
return instance;
}
public void setPollingListener(final PollingListener listener) {
this.listener = listener;
}
public void startPolling() {
poll = true;
poll(context);
}
public void stopPolling() {
poll = false;
}
private void poll(final Context context) {
RequestQueue queue = Volley.newRequestQueue(context);
final String url = BASE_URL + "events";
Log.i(TAG, url);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
ArrayList<Event> events = EventParser.parse(response);
if(listener != null) {
listener.onEventsReceived(events);
}
waitAndPoll();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(error.networkResponse == null || error.networkResponse.statusCode != 708) { //Timeout
if(listener != null) {
listener.onPollingError();
}
}
waitAndPoll();
}
});
queue.add(stringRequest);
}
private void waitAndPoll() {
if(poll) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
poll(context);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment