Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ConnectionService extends Service {
- public static final String ACTION_PING = "gagchat.ACTION_PING";
- public static final String ACTION_CONNECT = "gagchat.ACTION_CONNECT";
- public static final String ACTION_SHUT_DOWN = "gagchat.ACTION_SHUT_DOWN";
- private Socket mClient;
- private TreeSet<RowItem> mList = new TreeSet<RowItem>();
- private boolean mShutDown = false;
- private Handler mHandler;
- private ConnectionSerivceListener mListener;
- private final IBinder mBinder = new Binder();
- private Boolean connected = false;
- public Emitter.Listener onConnect = new Emitter.Listener() {
- @Override
- public void call(Object... args) {
- Log.d(Globals.DEBUGG_TAG, "Connected to websocket");
- }
- };
- public Emitter.Listener onError = new Emitter.Listener() {
- @Override
- public void call(Object... args) {
- Log.e(Globals.DEBUGG_TAG, "Websocket error");
- startService(startIntent(ConnectionService.this));
- }
- };
- public Emitter.Listener onMessage = new Emitter.Listener() {
- @Override
- public void call(Object... args) {
- Log.d(Globals.DEBUGG_TAG, "new message recieved");
- WakeLock wakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Chat Service");
- wakelock.acquire();
- final Response response = Response.deserializeList(args[0]);
- sendNotification(response);
- KeyManager keyManager = new KeyManager(getApplicationContext());
- String newMessage = "";
- try {
- newMessage = keyManager.decrypt(response.getMessage());
- } catch (Exception e) {
- e.printStackTrace();
- }
- RowItem rowItem = new RowItem(response.getFrom(), newMessage);
- mList.add(rowItem);
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- if (mListener != null) {
- mListener.newResponse(response);
- } else {
- sendNotification(response);
- }
- }
- });
- wakelock.release();
- }
- };
- public Emitter.Listener onDisconnect = new Emitter.Listener() {
- @Override
- public void call(Object... args) {
- connected = false;
- Log.d(Globals.DEBUGG_TAG, "Websocket disconnected");
- if (!mShutDown) {
- startService(startIntent(ConnectionService.this));
- } else {
- stopSelf();
- }
- }
- };
- private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- String message = intent.getStringExtra("message");
- mList.add(new RowItem("ich", message));
- Log.d(Globals.DEBUGG_TAG, "own message recieved");
- }
- };
- public static Intent startIntent(Context context) {
- Intent i = new Intent(context, ConnectionService.class);
- i.setAction(ACTION_CONNECT);
- return i;
- }
- public static Intent pingIntent(Context context) {
- Intent i = new Intent(context, ConnectionService.class);
- i.setAction(ACTION_PING);
- Log.d(Globals.DEBUGG_TAG, "Ping-Event");
- return i;
- }
- public static Intent closeIntent(Context context) {
- Intent i = new Intent(context, ConnectionService.class);
- i.setAction(ACTION_SHUT_DOWN);
- return i;
- }
- @Override
- public IBinder onBind(Intent intent) {
- return mBinder;
- }
- @Override
- public void onCreate() {
- super.onCreate();
- mHandler = new Handler();
- LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter("new-message"));
- Log.d(Globals.DEBUGG_TAG, "create Service " + this.toString());
- }
- @Override
- public void onDestroy() {
- LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
- super.onDestroy();
- Log.d(Globals.DEBUGG_TAG, "destroy Service " + this.toString());
- if (isConnected()) {
- mClient.close();
- }
- }
- public TreeSet<RowItem> getTreeSet() {
- return mList;
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- WakeLock wakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Chat Service");
- wakelock.acquire();
- mShutDown = false;
- if (mClient == null) {
- TokenManager tokenManager = new TokenManager(getApplicationContext());
- mClient = ConnectionManager.getInstance(tokenManager);
- }
- if (!isConnected()) {
- connected = true;
- mClient.connect();
- mClient.on("message", onMessage);
- mClient.on(Socket.EVENT_CONNECT, onConnect);
- mClient.on(Socket.EVENT_DISCONNECT, onDisconnect);
- mClient.on(Socket.EVENT_CONNECT_ERROR, onError);
- mClient.on(Socket.EVENT_ERROR, onError);
- } else {
- Log.d(Globals.DEBUGG_TAG, "websocket is already connected");
- }
- if (intent != null) {
- if(ACTION_PING.equals(intent.getAction())){
- JSONObject ping = new JSONObject();
- try {
- ping.put("ping", "ping");
- } catch (JSONException e) {
- e.printStackTrace();
- }
- if (isConnected()) {
- mClient.emit("ping", ping, new Ack() {
- @Override
- public void call(Object... args) {
- Log.d(Globals.DEBUGG_TAG, "recieved ping callback");
- }
- });
- }
- } else if (ACTION_SHUT_DOWN.equals(intent.getAction())) {
- mShutDown = true;
- if (isConnected()) {
- mClient.close();
- }
- }
- }
- if (intent == null || !intent.getAction().equals(ACTION_SHUT_DOWN)) {
- AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
- PendingIntent operation = PendingIntent.getService(this, 0, ConnectionService.pingIntent(this), PendingIntent.FLAG_NO_CREATE);
- if (operation == null) {
- operation = PendingIntent.getService(this, 0, ConnectionService.pingIntent(this), PendingIntent.FLAG_UPDATE_CURRENT);
- am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 6000, operation);
- Log.d(Globals.DEBUGG_TAG, "start alarm mamagner");
- }
- }
- wakelock.release();
- return START_STICKY;
- }
- public synchronized void setListener(ConnectionSerivceListener listener) {
- mListener = listener;
- }
- public synchronized boolean isConnected() {
- return mClient != null && connected;
- }
- public synchronized ArrayList<RowItem> getList() {
- ArrayList<RowItem> ret = new ArrayList<RowItem>();
- ret.addAll(mList);
- return ret;
- }
- private void sendNotification(Response response) {
- Notification.Builder notBuilder = new Notification.Builder(this);
- StringBuilder stringBuilder = new StringBuilder();
- notBuilder.setContentTitle("new message");
- notBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000});
- notBuilder.setLights(Color.GREEN, 3000, 3000);
- Intent intent = new Intent(this, ChatActivity.class);
- intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
- PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
- notBuilder.setContentIntent(pi);
- notBuilder.setSmallIcon(R.drawable.seven_icon);
- notBuilder.setOnlyAlertOnce(false);
- notBuilder.setAutoCancel(true);
- Notification.BigTextStyle bst = new Notification.BigTextStyle(notBuilder);
- bst.bigText(stringBuilder.toString());
- NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- nm.notify(0, bst.build());
- }
- public interface ConnectionSerivceListener {
- public void newResponse(Response response);
- }
- public class Binder extends android.os.Binder {
- public ConnectionService getService() {
- return ConnectionService.this;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement