socket

配置
compile files('libs/socket.io-client-0.8.3.jar')


//
设置连接服务地址 Socket socket = IO.socket(WAPI.WAPI_HTTP_IO); //使socket断开 socket.disconnect(); private void initSocket() { try { socket = IO.socket(WAPI.WAPI_HTTP_IO); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {// 与服务器创建连 @Override public void call(Object... args) { try { JSONObject object = new JSONObject().accumulate("username",PreferencesUtils.getString(HomeActivity.this, "HeadByName")); socket.emit("login", object);// 加入分组, 可以加入多个分组一个客户端可以存在多个分组(订阅模式) showCzNotify("", "正在实时监控"); LogUtils.v("Socket", "----------连接成功----------"); } catch (Exception e) { e.printStackTrace(); } } }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {// 连接断开了 @Override public void call(Object... args) { LogUtils.v("Socket", "==========断开连接==========="); showCzNotify("", "app处于后台时间过长啦!请打开app查看"); } }).on("push_to_" + PreferencesUtils.getString(HomeActivity.this, "HeadByName"),// 监听根据返回的数据更新界面 new Emitter.Listener() { @Override public void call(Object... args) { JSONObject jsonObject = (JSONObject) args[0]; Gson gson = new Gson(); final AlarmIgnoreMSG fromJson = gson.fromJson( jsonObject.toString(), AlarmIgnoreMSG.class); String event_level = fromJson.getData() .getEvent_level(); if ("alarm-level-y".equals(event_level)) { long[] vibrate = {0, 0, 0, 0}; showIntentActivityNotify("黄色预警", fromJson.getData() .getDetail(), 200, Notification.DEFAULT_LIGHTS, vibrate); } else if ("alarm-level-o".equals(event_level)) { long[] vibrate = {0, 2000, 1000, 3000}; showIntentActivityNotify("橙色预警", fromJson.getData() .getDetail(), 300, Notification.DEFAULT_VIBRATE, vibrate); } else if ("alarm-level-r".equals(event_level)) { long[] vibrate = {0, 2000, 1000, 3000}; showIntentActivityNotify("红色预警", fromJson.getData()// alarm-level-r .getDetail(), 400, Notification.DEFAULT_ALL, vibrate); } else if ("device_owner_alarm".equals(fromJson.getData() .getEvent_name())) { if (mErrdevWerning) { // 判断当前窗体的是不是dialog 是就break if (dialog != null && dialog.isShowing()) { return; } (HomeActivity.this).runOnUiThread(new Runnable() { public void run() { if (dialogErr == null) { showDialogErrView(fromJson); } else if (!dialogErr.isShowing()) { showDialogErrView(fromJson); } } }); } // } } else { long[] vibrate = {0, 0, 0, 0}; showIntentActivityNotify("通知", fromJson.getData() .getDetail(), 500, Notification.DEFAULT_LIGHTS, vibrate); } } }); // 开始连接 socket.connect(); }

 

posted on 2018-05-23 09:33  巫山老妖  阅读(361)  评论(0编辑  收藏  举报