Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2014
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.76 KB | None | 0 0
  1. public class ConnectionService extends Service {
  2.  
  3.     public static final String ACTION_PING = "gagchat.ACTION_PING";
  4.     public static final String ACTION_CONNECT = "gagchat.ACTION_CONNECT";
  5.     public static final String ACTION_SHUT_DOWN = "gagchat.ACTION_SHUT_DOWN";
  6.  
  7.     private Socket mClient;
  8.     private TreeSet<RowItem> mList = new TreeSet<RowItem>();
  9.     private boolean mShutDown = false;
  10.     private Handler mHandler;
  11.     private ConnectionSerivceListener mListener;
  12.  
  13.     private final IBinder mBinder = new Binder();
  14.  
  15.     private Boolean connected = false;
  16.  
  17.     public Emitter.Listener onConnect = new Emitter.Listener() {
  18.         @Override
  19.         public void call(Object... args) {
  20.             Log.d(Globals.DEBUGG_TAG, "Connected to websocket");
  21.         }
  22.     };
  23.     public Emitter.Listener onError = new Emitter.Listener() {
  24.  
  25.         @Override
  26.         public void call(Object... args) {
  27.             Log.e(Globals.DEBUGG_TAG, "Websocket error");
  28.             startService(startIntent(ConnectionService.this));
  29.         }
  30.     };
  31.  
  32.     public Emitter.Listener onMessage = new Emitter.Listener() {
  33.         @Override
  34.         public void call(Object... args) {
  35.             Log.d(Globals.DEBUGG_TAG, "new message recieved");
  36.  
  37.             WakeLock wakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Chat Service");
  38.             wakelock.acquire();
  39.  
  40.             final Response response = Response.deserializeList(args[0]);
  41.  
  42.             sendNotification(response);
  43.  
  44.             KeyManager keyManager = new KeyManager(getApplicationContext());
  45.  
  46.             String newMessage = "";
  47.             try {
  48.                 newMessage = keyManager.decrypt(response.getMessage());
  49.             } catch (Exception e) {
  50.                 e.printStackTrace();
  51.             }
  52.  
  53.             RowItem rowItem = new RowItem(response.getFrom(), newMessage);
  54.             mList.add(rowItem);
  55.  
  56.             mHandler.post(new Runnable() {
  57.  
  58.                 @Override
  59.                 public void run() {
  60.                     if (mListener != null) {
  61.                         mListener.newResponse(response);
  62.                     } else {
  63.                         sendNotification(response);
  64.                     }
  65.                 }
  66.             });
  67.             wakelock.release();
  68.         }
  69.     };
  70.  
  71.     public Emitter.Listener onDisconnect = new Emitter.Listener() {
  72.         @Override
  73.         public void call(Object... args) {
  74.             connected = false;
  75.             Log.d(Globals.DEBUGG_TAG, "Websocket disconnected");
  76.             if (!mShutDown) {
  77.                 startService(startIntent(ConnectionService.this));
  78.             } else {
  79.                 stopSelf();
  80.             }
  81.         }
  82.     };
  83.     private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  84.         @Override
  85.         public void onReceive(Context context, Intent intent) {
  86.             String message = intent.getStringExtra("message");
  87.  
  88.             mList.add(new RowItem("ich", message));
  89.  
  90.             Log.d(Globals.DEBUGG_TAG, "own message recieved");
  91.         }
  92.     };
  93.  
  94.     public static Intent startIntent(Context context) {
  95.         Intent i = new Intent(context, ConnectionService.class);
  96.         i.setAction(ACTION_CONNECT);
  97.         return i;
  98.     }
  99.  
  100.     public static Intent pingIntent(Context context) {
  101.         Intent i = new Intent(context, ConnectionService.class);
  102.         i.setAction(ACTION_PING);
  103.         Log.d(Globals.DEBUGG_TAG, "Ping-Event");
  104.         return i;
  105.     }
  106.  
  107.     public static Intent closeIntent(Context context) {
  108.         Intent i = new Intent(context, ConnectionService.class);
  109.         i.setAction(ACTION_SHUT_DOWN);
  110.         return i;
  111.     }
  112.  
  113.     @Override
  114.     public IBinder onBind(Intent intent) {
  115.         return mBinder;
  116.     }
  117.  
  118.     @Override
  119.     public void onCreate() {
  120.         super.onCreate();
  121.         mHandler = new Handler();
  122.  
  123.         LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter("new-message"));
  124.         Log.d(Globals.DEBUGG_TAG, "create Service " + this.toString());
  125.     }
  126.  
  127.     @Override
  128.     public void onDestroy() {
  129.         LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
  130.  
  131.         super.onDestroy();
  132.         Log.d(Globals.DEBUGG_TAG, "destroy Service " + this.toString());
  133.         if (isConnected()) {
  134.             mClient.close();
  135.         }
  136.     }
  137.  
  138.     public TreeSet<RowItem> getTreeSet() {
  139.         return mList;
  140.     }
  141.  
  142.     @Override
  143.     public int onStartCommand(Intent intent, int flags, int startId) {
  144.         WakeLock wakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Chat Service");
  145.         wakelock.acquire();
  146.  
  147.         mShutDown = false;
  148.         if (mClient == null) {
  149.             TokenManager tokenManager = new TokenManager(getApplicationContext());
  150.  
  151.             mClient = ConnectionManager.getInstance(tokenManager);
  152.         }
  153.  
  154.         if (!isConnected()) {
  155.             connected = true;
  156.             mClient.connect();
  157.             mClient.on("message", onMessage);
  158.             mClient.on(Socket.EVENT_CONNECT, onConnect);
  159.             mClient.on(Socket.EVENT_DISCONNECT, onDisconnect);
  160.             mClient.on(Socket.EVENT_CONNECT_ERROR, onError);
  161.             mClient.on(Socket.EVENT_ERROR, onError);
  162.         } else {
  163.             Log.d(Globals.DEBUGG_TAG, "websocket is already connected");
  164.         }
  165.  
  166.         if (intent != null) {
  167.             if(ACTION_PING.equals(intent.getAction())){
  168.                 JSONObject ping = new JSONObject();
  169.                 try {
  170.                     ping.put("ping", "ping");
  171.                 } catch (JSONException e) {
  172.                     e.printStackTrace();
  173.                 }
  174.  
  175.                 if (isConnected()) {
  176.                     mClient.emit("ping", ping, new Ack() {
  177.                         @Override
  178.                         public void call(Object... args) {
  179.                             Log.d(Globals.DEBUGG_TAG, "recieved ping callback");
  180.                         }
  181.                     });
  182.                 }
  183.             } else if (ACTION_SHUT_DOWN.equals(intent.getAction())) {
  184.                 mShutDown = true;
  185.                 if (isConnected()) {
  186.                     mClient.close();
  187.                 }
  188.             }
  189.         }
  190.  
  191.         if (intent == null || !intent.getAction().equals(ACTION_SHUT_DOWN)) {
  192.             AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
  193.             PendingIntent operation = PendingIntent.getService(this, 0, ConnectionService.pingIntent(this), PendingIntent.FLAG_NO_CREATE);
  194.             if (operation == null) {
  195.                 operation = PendingIntent.getService(this, 0, ConnectionService.pingIntent(this), PendingIntent.FLAG_UPDATE_CURRENT);
  196.                 am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 6000, operation);
  197.                 Log.d(Globals.DEBUGG_TAG, "start alarm mamagner");
  198.             }
  199.         }
  200.  
  201.         wakelock.release();
  202.         return START_STICKY;
  203.     }
  204.  
  205.     public synchronized void setListener(ConnectionSerivceListener listener) {
  206.         mListener = listener;
  207.     }
  208.  
  209.     public synchronized boolean isConnected() {
  210.         return mClient != null && connected;
  211.     }
  212.  
  213.     public synchronized ArrayList<RowItem> getList() {
  214.         ArrayList<RowItem> ret = new ArrayList<RowItem>();
  215.         ret.addAll(mList);
  216.         return ret;
  217.     }
  218.  
  219.     private void sendNotification(Response response) {
  220.         Notification.Builder notBuilder = new Notification.Builder(this);
  221.         StringBuilder stringBuilder = new StringBuilder();
  222.  
  223.         notBuilder.setContentTitle("new message");
  224.         notBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000});
  225.         notBuilder.setLights(Color.GREEN, 3000, 3000);
  226.  
  227.         Intent intent = new Intent(this, ChatActivity.class);
  228.         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
  229.         PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  230.         notBuilder.setContentIntent(pi);
  231.         notBuilder.setSmallIcon(R.drawable.seven_icon);
  232.         notBuilder.setOnlyAlertOnce(false);
  233.         notBuilder.setAutoCancel(true);
  234.         Notification.BigTextStyle bst = new Notification.BigTextStyle(notBuilder);
  235.         bst.bigText(stringBuilder.toString());
  236.  
  237.         NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  238.         nm.notify(0, bst.build());
  239.     }
  240.  
  241.     public interface ConnectionSerivceListener {
  242.         public void newResponse(Response response);
  243.     }
  244.  
  245.     public class Binder extends android.os.Binder {
  246.  
  247.         public ConnectionService getService() {
  248.             return ConnectionService.this;
  249.         }
  250.     }
  251. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement