1. 程式人生 > >物聯網封裝基類

物聯網封裝基類

public abstract class MyBaseActivity extends BaseFMActivity implements OnSocketListener, OnReceiveListener {
    private static final int MSG_WHAT = 0x089;
    //佈局繫結物件
    Unbinder unbinder;
    //socketclient物件
    public SocketClient mSocketClient;
    public int flag;//操作指令

//    public Timer mTimer;
//    public TimerTask mTimerTask;

    @Override
    protected void bindView() {
//        BarUtils.setTranslucentStatusBar(getBindActivity());
        BarUtils.setColorNoTranslucent(this, getCol(R.color.apple_blue));
        mActivity = getBindActivity();
        unbinder = ButterKnife.bind(getBindActivity());//繫結佈局
        flag = -1;
        connectSocket();
        setSocketListener();
        initView();
    }

    /* 連線監聽*/
    @Override
    public void onConnect(int flag) {
        ToastUtils.showToast("閘道器連線成功");
        LogUtils.e("連線成功");
        handler.removeMessages(MSG_WHAT);
    }

    @Override
    public void onConnectError(Exception ex, int flag) {
        if (ex != null)
            LogUtils.e("連線失敗" + ex.getMessage() + flag);
        handler.removeMessages(MSG_WHAT);
        dissmissLoading();
        ToastUtils.showToast("閘道器連線失敗" + (ex != null ? ex.getMessage() : ""));

    }

    @Override
    public void onConnecting() {
        showLoading(this, "連線閘道器中...");
        LogUtils.e("連線中");
        startTime();//設定超時標識
    }

    @Override
    public void onEnd(Exception ex) {
        if (ex != null)
            ex.printStackTrace();
        handler.removeMessages(MSG_WHAT);
        LogUtils.e("結束連線");
    }

    public int reConnectNum;

    @Override
    public void onClose(Exception ex) {
        if (ex != null)
            ex.printStackTrace();
        handler.removeMessages(MSG_WHAT);
        LogUtils.e("連線關閉");
        reConnectNum++;
    }

    @Override
    public void onDataReply(UnpackData data) {
        LogUtils.e("獲取到資料包");
//        ToastUtils.showToast(data.toString());
        flag = -1;
        handler.removeMessages(MSG_WHAT);
    }

    /* 連線監聽結束 */

    public void connectSocket() {
        mSocketClient = SocketClient.getInstance((MyBaseActivity) getBindActivity(), flag);//初始化socket連線
        mSocketClient.addOnReceiveListener((MyBaseActivity) getBindActivity());
    }

    public void setSocketListener() {
        mSocketClient.setOnSocketListener((MyBaseActivity) getBindActivity());
    }

    /**
     * 重連線
     */
    public void reConnect(int flag) {
        LogUtils.e("重連");
        showLoading(getBindActivity(), "連線閘道器中...");
        startTime();
        if (mSocketClient != null) {
            mSocketClient.reConnect(flag);
        } else {
            connectSocket();
        }
    }

    /**
     * 是否連線
     *
     * @return
     */
    public boolean isOpen() {
        if (mSocketClient != null) {
            return mSocketClient.isConnected();
        }
        return false;
    }

    /**
     * 傳送資料
     *
     * @param data
     */
    public void sendData(byte[] data) {
        if (mSocketClient != null) {
            showLoading(getBindActivity(), getStr(R.string.send_instruction));
            mSocketClient.sendData(new ByteBufferList(data));
            startTime();
        }
    }


    public void sendDataFlag(byte[] data, int flag) {
        if (this.flag != flag) {
            reConnectNum = 0;
        }
        if (isOpen()) {
            sendData(data);
            this.flag = flag;
        } else {
            reConnect(flag);
        }
    }

    /**
     * 關閉連線
     */
    public void closeSocket() {
        if (mSocketClient != null) {
            mSocketClient.close();
            mSocketClient = null;
        }
    }

    /**
     * 繫結Activity
     *
     * @return
     */
    protected abstract Activity getBindActivity();

    /**
     * 初始化
     */
    protected abstract void initView();

    @Override
    protected void onResume() {
        super.onResume();
        if (mSocketClient != null)
            mSocketClient.setOnSocketListener((MyBaseActivity) getBindActivity());
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mSocketClient != null)
            mSocketClient.removeOnSocketListener((MyBaseActivity) getBindActivity());
    }

    /**
     * Activity銷燬操作
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSocketClient != null) {
            mSocketClient.removeOnReceiceListener((MyBaseActivity) getBindActivity());
        }
        dialog = null;
        builer = null;
        msgText = null;
        unbinder.unbind();
    }

    AlertDialog dialog;
    AlertDialog.Builder builer;
    TextView msgText;

    public void showLoading(Context context, String msg) {
        if (builer == null) {
            builer = new AlertDialog.Builder(context, R.style.myDialog);
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_loading, null);
            msgText = (TextView) view.findViewById(R.id.msg);
            builer.setView(view);
        }
        msgText.setText(msg);
        if (dialog == null) {
            dialog = builer.create();
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    return false;
                }
            });
        }
        dialog.show();
    }


    public void dissmissLoading() {
        if (dialog != null)
            dialog.dismiss();
    }

    public void setLoadingMsg(String msg) {
        if (msgText != null)
            msgText.setText(msg);
    }


    private void startTime() {
        handler.sendEmptyMessageDelayed(MSG_WHAT, Constant.TIMEOUT_LONG);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_WHAT) {
                onConnectError(new RuntimeException("連線超時"), flag);//此處已經處理了所有連線失敗的邏輯
            }
        }
    };
}