Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.oncall.app;
- import android.app.Application;
- import android.text.TextUtils;
- import com.android.volley.Request;
- import com.android.volley.RequestQueue;
- import com.android.volley.toolbox.Volley;
- import java.util.ArrayList;
- import io.socket.client.IO;
- import io.socket.client.Socket;
- import io.socket.emitter.Emitter;
- /**
- * Created by Bradly on 12/29/2017.
- */
- public class AppController extends Application{
- public static final String TAG = AppController.class.getSimpleName();
- private RequestQueue mRequestQueue;
- private static AppController mInstance;
- private Socket mSocket; // A 2 way connection between the server and the phone running this app
- private ArrayList<Emitter.Listener> socketListeners;
- private ArrayList<String> socketEvents;
- @Override
- public void onCreate(){
- super.onCreate();
- socketListeners= new ArrayList<>();
- mInstance = this; // Save reference to initialized object for future reference
- // Initialize the on call api socket
- try{
- IO.Options opts = new IO.Options();
- opts.forceNew = true;
- opts.reconnection = true;
- opts.secure = true;
- mSocket = IO.socket(AppConfig.API_SERVER_ADDRESS, opts);
- } catch (Exception e){
- e.printStackTrace();
- }
- }
- public static synchronized AppController getInstance() {
- return mInstance;
- }
- public RequestQueue getRequestQueue() {
- if (mRequestQueue == null) {
- mRequestQueue = Volley.newRequestQueue(getApplicationContext());
- }
- return mRequestQueue;
- }
- public <T> void addToRequestQueue(Request<T> req, String tag) {
- req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
- getRequestQueue().add(req);
- }
- public Socket getSocket(){
- return mSocket;
- }
- public void connectSocket(){
- if(socketListeners.size() <= 0)
- System.out.println("[ERR] => (AppController) Socket connection requested, but no listeners registered.");
- else
- mSocket.connect();
- }
- // Add an event listener and register it with the socket
- public void addListener(String event, Emitter.Listener listener){
- if(!(event.equals("") || event.equals(" "))) {
- socketListeners.add(listener);
- socketEvents.add(event);
- mSocket.on(event, listener);
- }
- else{
- System.out.println("[ERR] => (AppController) Tried to add listener with empty event.");
- }
- }
- // Remove listeners, and disconnect the socket
- public void disconnectSocket(){
- for(int i = 0; i < socketListeners.size(); i++){
- mSocket.off(socketEvents.get(i), socketListeners.get(i));
- }
- mSocket.disconnect();
- }
- public void shutdown(){
- disconnectSocket();
- System.out.println("[STAT] => (AppController) Shutdown requested, shutting down.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement