SocketIO的工具类
public class SocketIoService extends Service {
private static final String TAG = "SocketIoService";
public static String SOCKET_HOST = Constant.websocket_server;//这个是后台给的地址,根据自家的地址写上去即可
private Socket mSocket;
private boolean isOpen;//打开的状态
private MyReceiver receiver;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
@Override
public void onCreate() {
super.onCreate();
SocketConnect();
LogUtils.debug(TAG, "onCreate");
IntentFilter filter = new IntentFilter();
filter.addAction("com.dingler.alarm");
receiver = new MyReceiver();
registerReceiver(receiver, filter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
LogUtils.debug(TAG, "onStartCommand");
// SocketConnect();
// return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// closeSocket();
unregisterReceiver(receiver);
stopForeground(true);//是否关闭前台服务
LogUtils.debug(TAG, "onDestroy");
}
@Override
public boolean stopService(Intent name) {
LogUtils.debug(TAG, "stopService");
return super.stopService(name);
}
// 这里使用binder 主要是为了在activity中进行通讯, 大家也可以使用EventBus进行通讯
public class MyBinder extends Binder {
public SocketIoService getService() {
return SocketIoService.this;
}
}
//连接socket io
public void SocketConnect() {
if (mSocket == null) {
try {
Options ops = new Options();
ops.setReconnection(false);
ops.timeout = 5000;
mSocket = IO.socket(SOCKET_HOST);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
mSocket.connect();
isOpen = true;
mSocket.on("login", args -> {
JSONObject data = (JSONObject) args[0];
LogUtils.debug(TAG, "login:" + data.toString());
});
mSocket.on("room", args -> {
JSONObject data = (JSONObject) args[0];
LogUtils.debug(TAG, "room:" + data.toString());
});
mSocket.on("data", args -> {
JSONObject data = (JSONObject) args[0];
RunControlInfo runControlInfo = new Gson().fromJson(data.toString(), new TypeToken() {
}.getType());
RunSubject.getInstance().update(runControlInfo);
LogUtils.debug(TAG, "data:" + data.toString());
});
mSocket.on("rtdata", args -> {
JSONObject data = (JSONObject) args[0];
RunControlInfo runControlInfo = new Gson().fromJson(data.toString(), new TypeToken() {
}.getType());
RunSubject.getInstance().update(runControlInfo);
if(!data.toString().contains("Level")){
LogUtils.debug(TAG, "rtdata:" + data.toString());
}
});
mSocket.on("alarm", args -> {
JSONObject data = (JSONObject) args[0];
LogUtils.debug(TAG, "alarm:" + data.toString());
OfflineInfo offlineInfo = new Gson().fromJson(data.toString(), new TypeToken() {
}.getType());
AlarmSubject.getInstance().update(offlineInfo);
Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ic_launcher);
if ("Offline".equals(offlineInfo.getTnm()) && offlineInfo.getVal() == 1) {
RunControlInfo runControlInfo = new RunControlInfo();
runControlInfo.setBnm(offlineInfo.getBnm());
runControlInfo.setTds(offlineInfo.getTds());
// RunSubject.getInstance().update(runControlInfo);
String title = "设备离线";
String str = offlineInfo.getName() + offlineInfo.getTds();
Intent intent = new Intent(getContext(), DeviceFragment.class);
intent.putExtra("page", 0);
PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationUtils.notifyWithIntent(title, str, bitmap, pendingIntent);
}
});
mSocket.on("control", args -> {
for (Object obj : args) {
if (obj instanceof Throwable) {
((Throwable) obj).printStackTrace();
}
LogUtils.debug(TAG, "控制" + obj.toString());
ControlInfo controlInfo = new Gson().fromJson(obj.toString(), new TypeToken() {
}.getType());
RunSubject.getInstance().setResult(controlInfo);
}
});
mSocket.on("control_res", args -> {
for (Object obj : args) {
if (obj instanceof Throwable) {
((Throwable) obj).printStackTrace();
}
LogUtils.debug(TAG, "下发指令" + obj.toString());
ControlInfo controlInfo = new Gson().fromJson(obj.toString(), new TypeToken() {
}.getType());
RunSubject.getInstance().setResult(controlInfo);
}
});
mSocket.on("connect", args -> {
for (Object obj : args) {
if (obj instanceof Throwable) {
((Throwable) obj).printStackTrace();
}
LogUtils.debug(TAG, "socket 连接" + obj.toString());
login();
}
});
mSocket.on("reconnect", args -> {
for (Object obj : args) {
if (obj instanceof Throwable) {
((Throwable) obj).printStackTrace();
}
LogUtils.debug(TAG, "socket 重连" + obj.toString());
}
});
mSocket.on("error", args -> {
for (Object obj : args) {
if (obj instanceof Throwable) {
((Throwable) obj).printStackTrace();
}
LogUtils.debug(TAG, "错误" + obj.toString());
}
});
mSocket.on("connect_error", args -> {
for (Object obj : args) {
if (obj instanceof Throwable) {
((Throwable) obj).printStackTrace();
}
LogUtils.debug(TAG, "连接错误" + obj.toString());
}
});
mSocket.on("disconnect", args -> {
for (Object obj : args) {
if (obj instanceof Throwable) {
((Throwable) obj).printStackTrace();
}
LogUtils.debug(TAG, "断开连接" + obj.toString());
}
});
}
private void login(){
JSONObject jsonObject1 = new JSONObject();
try {
jsonObject1.put("username", SPUtils.getStringFromSP("username"));
jsonObject1.put("token", SPUtils.getStringFromSP("token"));
sendMsg("login",jsonObject1);
} catch (JSONException e) {
e.printStackTrace();
}
}
//关闭socket io
public void closeSocket() {
isOpen = false;
if (mSocket != null) {
mSocket.off();
mSocket.disconnect();
}
}
//判断socket io 是否连接成功
public boolean isOpen() {
return isOpen;
}
public void sendMsg(String room, JSONObject jsonObject) {
if (mSocket != null && isOpen) {
mSocket.emit(room, jsonObject);
LogUtils.debug(TAG, "ws- 发送 message");
}
}
//在service中创建回调接口
private OnDataReceiverListener mListener;
//设置监听
public void setOnDataReceiverListener(OnDataReceiverListener listener) {
mListener = listener;
}
public interface OnDataReceiverListener {
void onTextMsg(String text);
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("com.dingler.alarm".equals(intent.getAction())) {
String offline = intent.getStringExtra("offline");
String online = intent.getStringExtra("online");
String bnm =intent.getStringExtra("bnm");
String tnm =intent.getStringExtra("tnm");
int value =intent.getIntExtra("value",0);
if(!TextUtils.isEmpty(bnm) && !TextUtils.isEmpty(tnm)){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("boxname", bnm);
jsonObject.put("signalsource", "YD");
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject();
json.put(tnm,value);
jsonObject.put("control", json);
} catch (JSONException e) {
e.printStackTrace();
}
//发送消息
sendMsg("control",jsonObject);
LogUtils.debug("控制",jsonObject.toString());
}else if(!TextUtils.isEmpty(online) || !TextUtils.isEmpty(offline)){
JSONObject jsonObject = new JSONObject();
try {
//进入/离开房间
//传1,上线;传0,下线
if(!TextUtils.isEmpty(online)){
jsonObject.put(online, 1);
}else if(!TextUtils.isEmpty(offline)){
jsonObject.put(offline, 0);
}
sendMsg("room", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}else {
} }
}
}
}
RunSubject工具类
public class RunSubject implements SubjectRun {
private static final RunSubject ourInstance = new RunSubject();
public static RunSubject getInstance() {
return ourInstance;
}
private RunControlInfo runControlInfo;
private RunSubject() {
}
private List datas = new ArrayList<>();
private ObserverControl observerControl;
@Override
public void add(ObserverRun observerRun) {
datas.add(observerRun);
}
@Override
public void remove(ObserverRun observerRun) {
datas.remove(observerRun);
}
@Override
public void refresh() {
if (datas.size() == 0) {
return;
}
for (int i = 0; i < datas.size(); i++) {
datas.get(i).update(runControlInfo);
}
}
@Override
public void removeAll() {
if (datas != null && datas.size() > 0) {
datas.clear();
}
}
public void update(RunControlInfo runControlInfo) {
this.runControlInfo = runControlInfo;
refresh();
}
public void setResult(ControlInfo controlInfo) {
if(observerControl !=null){
observerControl.controlResult(controlInfo);
}
}
public void setObserverControl(ObserverControl observerControl) {
this.observerControl = observerControl;
}
}
SubjectRun工具类
public interface SubjectRun {
void add(ObserverRun observerRun);
void remove(ObserverRun observerRun);
void refresh();
void removeAll();
}
ObserverRun工具类
public interface ObserverRun {
void update(RunControlInfo runControlInfo);
}
RunControlInfo实体类
public class RunControlInfo {
/**
* bnm : MZZBZ
* tnm : Screen_Rt_Current
* val : 5.3400
* ts : 2019-12-24 11:24:58.31
* tds : 通道 设备 格栅电流
*/
private String bnm;
private String tnm;
private float val;
private String ts;
private String tds;
public String getBnm() {
return bnm;
}
public void setBnm(String bnm) {
this.bnm = bnm;
}
public String getTnm() {
return tnm;
}
public void setTnm(String tnm) {
this.tnm = tnm;
}
public float getVal() {
return val;
}
public void setVal(float val) {
this.val = val;
}
public String getTs() {
return ts;
}
public void setTs(String ts) {
this.ts = ts;
}
public String getTds() {
return tds;
}
public void setTds(String tds) {
this.tds = tds;
}
}
ObserverControl实体类
public interface ObserverControl {
void controlResult(ControlInfo controlInfo);
}
绑定serviceio服务MainActivity
if (!ServiceUtils.isServiceExit(this)) {
Intent intent = new Intent(getContext(), SocketIoService.class);
isBind = bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
handler.post(runnable);
startService(intent);
}
//得到service的对象后,调用发送信息方法即可
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
SocketIoService.MyBinder binder = (SocketIoService.MyBinder) service;
mService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
LogUtils.debug("TAG", "onServiceDisconnected:");
}
};
Runnable runnable = (new Runnable() {
@Override
public void run() {
if (mService == null) {
handler.postDelayed(this, 500);
LogUtils.debug("TAG", "定时");
} else {
handler.removeCallbacks(this);
LogUtils.debug("TAG", "结束定时");
}
}
});
activity和fragment中的使用
@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
RunSubject.getInstance().add(this);
RunSubject.getInstance().setObserverControl(this);
}
@Override
public void onDetach() {
super.onDetach();
RunSubject.getInstance().remove(this);
}
@Override
public void update(RunControlInfo runControlInfo) {
//更新消息处理
}