基于OKhttp循环队列发送心跳包,上传,多条上传 管理类

package com.omniteaching.otscale.system.formula;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.omniteaching.otscale.model.formulaC.FormulaMutilInvoiceInfo;
import com.omniteaching.otscale.system.scale.utils.WeightFormat;
import com.omniteaching.otscale.ui.formula.http.FormulaOkHttpListener;
import com.omniteaching.otscale.ui.formula.http.IUploadMultipleListener;
import com.omniteaching.otscale.ui.formula.model.FormulaMulitTasks;
import com.omniteaching.otscale.ui.formula.model.FormulaRegisterModel;
import com.omniteaching.otscale.utils.Globals;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

import static com.omniteaching.otscale.ui.formula.http.FormulaHttps.AUTHORIZATION;
import static com.omniteaching.otscale.ui.formula.http.FormulaHttps.URL_MULTIPLE_REGISTGER_FORMULA;
import static com.omniteaching.otscale.ui.formula.http.FormulaHttps.getLocationToken;

/**
 * Created by Administrator on 2016/4/26.
 */
public class FormulaMutilHttpManager
{
    private static final String TAG = FormulaMutilHttpManager.class.getSimpleName();
    private static FormulaMutilHttpManager mInstance;
    private static Context mContext;
    //    private WifiManager.MulticastLock mLock;//UDP解锁刷新

    public static final int OFFLINE = 0; // 离线
    public static final int IDLE = 1; // 空闲
    public static final int WORKING = 2; // 工作中
    public static final int PAUSE = 4; // 暂停
    public static final int CANCEL = 8; // 取消

    public static final String CANCEL_STRING = "cancel";
    /**
     * 消息格式 请求时间
     */
    //KEY
    public static final String DeviceKey = "Device";
    public static final String TitleKey = "Title";
    public static final String MaxRangeKey = "MaxRange";
    public static final String PrecisionKey = "Precision";
    public static final String TeamKey = "Team";
    public static final String IPAddressKey = "IPAddress";
    public static final String PercentKey = "Percent";
    public static final String IDKey = "ID";
    public static final String MissionIDKey = "MissionID";
    public static final String MissionDetailIDKey = "MissionDetailID";
    public static final String SaltKey = "Salt";
    public static final String WeightKey = "Weight";
    public static final String DeviationWeightKey = "DeviationWeight";
    public static final String MaterialTitleKey = "MaterialTitle";
    public static final String RecipeIDKey = "RecipeID";
    public static final String LastHeartBeatKey = "LastHeartBeat";
    public static final String StatusKey = "Status";
    public static final String StatusTitleKey = "StatusTitle";
    public static final String MissionetailKey = "Missionetail";

    private static final String SCALES = "/SCALES";
    private static final String TASKS = "/tasks";
    private String URL_MULTIPLE_UPDATE_FORMULA;
    private boolean isFlag;
    private HashMap, HeartbeatMutiple> mMutipleHashMap;
    private ChangeMultiState mChangeMultiState;
    private UpdateMulti mUpdateMultiFormula;
    private DecimalFormat mDecimalFormat;


    public static FormulaMutilHttpManager getInstance(Context context)
    {
        if (mInstance == null)
        {
            synchronized (FormulaMutilHttpManager.class)
            {
                if (mInstance == null)
                {
                    mInstance = new FormulaMutilHttpManager(context);
                }
            }
        }
        return mInstance;
    }

    public FormulaMutilHttpManager(Context context)
    {
        super();
        mContext = context;
        initVarible();
    }


    private void initVarible()
    {
        mMutipleHashMap = new HashMap, HeartbeatMutiple>();
        isFlag = true;
    }

    /**
     * 销毁实例
     */
    public void destroyInstance()
    {
        mInstance = null;
        mMutipleHashMap = null;
    }

    /**
     * 发送心跳包
     *
     * @param model    设备名必须传 Device
     * @param listener 成功失败超时接口
     * @param context
     */
    public void sendHeartbeatPackets(FormulaRegisterModel model,
                                     final FormulaOkHttpListener listener, Context context)
    {
        if (mMutipleHashMap != null)
        {
            if (model != null)
            {
                HeartbeatMutiple heartbeatMutiple;
                if (mMutipleHashMap.containsKey(model.getDevice()))
                {
                    heartbeatMutiple = mMutipleHashMap.get(model.getDevice());
                } else
                {
                    heartbeatMutiple = new HeartbeatMutiple(model, listener, context, 10, 3);
                    mMutipleHashMap.put(model.getDevice(), heartbeatMutiple);
                }
                if (heartbeatMutiple != null)
                {
                    if (!heartbeatMutiple.isAlive())
                        heartbeatMutiple.start();
                }
            }
        }
    }

    /**
     * 关闭心跳发送
     */
    public void closeHeartbeatPackets(String deviceID)
    {
        if (!TextUtils.isEmpty(deviceID))
        {
            if (mMutipleHashMap != null)
            {
                HeartbeatMutiple heartbeatMutiple = mMutipleHashMap.get(deviceID);
                if (heartbeatMutiple != null)
                {
                    heartbeatMutiple.unRegistHeartbeat();
                    mMutipleHashMap.remove(deviceID);
                    heartbeatMutiple = null;
                }
            }
        }
    }

    private class HeartbeatMutiple extends Thread
    {
        private OkHttpClient mOkHttpClient;
        private FormulaRegisterModel mModel;
        private FormulaOkHttpListener mListener;
        private Context mContext;
        private boolean isSafety;
        private int OktimeOut;// ok超时时间
        private int heartbeatTime;// 隔几秒发送

        HeartbeatMutiple(FormulaRegisterModel model, final
        FormulaOkHttpListener listener, Context context, int oktimeOut, int heartbeatTime)
        {
            mModel = model;
            mListener = listener;
            mContext = context;
            mOkHttpClient = new OkHttpClient();
            //设置OK超时
            isSafety = true;
            OktimeOut = oktimeOut;
            mOkHttpClient.setConnectTimeout(OktimeOut, TimeUnit.SECONDS);
            this.heartbeatTime = heartbeatTime;
        }

        @Override
        public void run()
        {
            while (isSafety)
            {
                registHeartbeat(mModel, mListener, mContext);
                try
                {
                    Thread.sleep(heartbeatTime * 1000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

        }

        private void registHeartbeat(FormulaRegisterModel model, final
        FormulaOkHttpListener listener, Context context)
        {
            if (context == null)
            {
                listener.onError(null, null);
                return;
            }
            String handlerValue = getLocationToken(context);
            if (TextUtils.isEmpty(handlerValue))
            {
                listener.onError(null, null);
                return;
            }
//            mUpLoadMultipleArrayList = new OkHttpClient();
            if (model == null)
                return;

            RequestBody build = new FormEncodingBuilder()
                    .add(FormulaMutilHttpManager.DeviceKey, model.getDevice())
//                    .add(FormulaMultipleManager.TitleKey, model.getTitle())
//                    .add(FormulaMultipleManager.MaxRangeKey, String.valueOf(model.getMaxRange()))
//                    .add(FormulaMultipleManager.TeamKey, model.getTeam())
//                    .add(FormulaMultipleManager.IPAddressKey, model.getIPAddress())
//                    .add(FormulaMultipleManager.PercentKey, String.valueOf(model.getPercent()))
//                    .add(FormulaMultipleManager.PrecisionKey, String.valueOf(model.getPrecision())).
                    .build();
            final Request request = new Request
                    .Builder()
                    .url(URL_MULTIPLE_REGISTGER_FORMULA)
                    .addHeader(AUTHORIZATION, handlerValue)
                    .post(build)
                    .build();

            mOkHttpClient.newCall(request)
                    .enqueue(new Callback()
                    {
                        @Override
                        public void onFailure(Request request, IOException e)
                        {
                            if (listener != null)
                                listener.onError(request, e);

                        }

                        @Override
                        public void onResponse(Response response) throws IOException
                        {
                            if (null != listener)
                            {
                                switch (response.code())
                                {
                                    case HttpURLConnection.HTTP_BAD_REQUEST:
                                        String ss = response.toString();
                                        listener.onError(response.request(), null);
                                        break;
                                    case HttpURLConnection.HTTP_OK:
                                        Gson gson = new Gson();
                                        String string = response.body().string();
                                        FormulaMulitTasks result = gson.fromJson(string, new TypeToken()
                                        {
                                        }.getType());
                                        listener.onResponse(result, null, null);
                                        break;
                                    default:
                                        listener.onError(response.request(), null);
                                        break;

                                }
                            }
                        }
                    });


        }

        void unRegistHeartbeat()
        {
            this.interrupt();
            isSafety = false;
        }

    }


    /**
     * 上传 多条
     *
     * @param list                   上传列表
     * @param context                上下文
     * @param listener               回调接口
     * @param uploadMultipleListener 状态回调
     */
    public void updateMultiFormulaInfo(ArrayList list, Context context,
                                       final FormulaOkHttpListener listener, IUploadMultipleListener uploadMultipleListener)
    {
        if (mUpdateMultiFormula != null)
        {
            mUpdateMultiFormula.closeRun();
            mUpdateMultiFormula = null;
        }
        if(list == null)
        {
            return;
        }
        mUpdateMultiFormula = new UpdateMulti(list, context, listener, uploadMultipleListener);
        if (!mUpdateMultiFormula.isAlive())
            mUpdateMultiFormula.start();
    }


    private class UpdateMulti extends Thread
    {
        private ArrayList mList;
        private Context mContext;
        private FormulaOkHttpListener mListener;
        private IUploadMultipleListener mUploadMultipleListener;
        private boolean isSafety;
        private LinkedBlockingDeque mSendMsgQuene;
        private Call mCall;
        private OkHttpClient mOkHttpClient;
        private ArrayList mUpLoadMultipleArrayList;
        private ArrayList successList;
        private ArrayList errorList;

        UpdateMulti(ArrayList list, Context context,
                    final FormulaOkHttpListener listener, IUploadMultipleListener uploadMultipleListener)
        {
//            mList = list;
            mDecimalFormat = new DecimalFormat();
            mList = new ArrayList();
            mList.addAll(list);
            mContext = context;
            mListener = listener;
            mUploadMultipleListener = uploadMultipleListener;
            isFlag = true;
            isSafety = true;
            mSendMsgQuene = new LinkedBlockingDeque();
            mOkHttpClient = new OkHttpClient();
            mUpLoadMultipleArrayList = new ArrayList();
            successList = new ArrayList();
            errorList = new ArrayList();
        }

        @Override
        public void run()
        {
            super.run();
            updateInfo(mList, mContext, mListener, mUploadMultipleListener);
        }

        private void closeRun()
        {
            isSafety = false;
            if (mList != null)
                mList.clear();
            if (mUpLoadMultipleArrayList != null)
                mUpLoadMultipleArrayList.clear();
            if (successList != null)
                successList.clear();
            if (errorList != null)
                errorList.clear();
            mList = null;
            mUpLoadMultipleArrayList = null;
            successList = null;
            errorList = null;
            mListener = null;
            mContext = null;
            mOkHttpClient = null;
            mDecimalFormat = null;
        }

        /**
         * @param list     多个配料上传list
         * @param context
         * @param listener 回调
         */
        void updateInfo(ArrayList list, Context context,
                        final FormulaOkHttpListener listener, IUploadMultipleListener uploadMultipleListener)
        {
            if(list==null)
                return;
//            ArrayList success = {0};//200
//            final int[] error1 = {0};//设备ID出错 not_in_weight_or_donot_weight_anything: 未称重,或者无称重数值
//            final int[] error2 = {0};//未找到相应的台秤信息
//            final int[] fail = {0};//失败(网络异常,地址不正确,超时)
            for (FormulaMutilInvoiceInfo formulaUpLoadMultiple : list)
            {
                putQuene(formulaUpLoadMultiple);
                updateFormulaInfo(context, listener, new CallBack()
                {
                    @Override
                    public void onCallback(int start, String resualt)
                    {
                        switch (start)
                        {
                            case HttpURLConnection.HTTP_BAD_REQUEST:
                                errorList.add(HttpURLConnection.HTTP_BAD_REQUEST);
                                break;
                            case HttpURLConnection.HTTP_OK:
                                Gson gson = new Gson();
                                FormulaMulitTasks result = gson.fromJson(resualt, new TypeToken()
                                {
                                }.getType());
                                successList.add(result);
//
                                break;
                            case HttpURLConnection.HTTP_NOT_FOUND:
                                errorList.add(HttpURLConnection.HTTP_NOT_FOUND);
                                break;

                            case 555:
                                errorList.add(555);
                                break;
                        }
                    }
                });
            }
            if (uploadMultipleListener != null)
                uploadMultipleListener.onStatus(successList, errorList);
        }

        private void putQuene(FormulaMutilInvoiceInfo formulaUpLoadMultiple)
        {
            isSafety = true;
            if (mUpLoadMultipleArrayList != null)
            {
                mUpLoadMultipleArrayList.add(formulaUpLoadMultiple);
            }
        }

        /**
         * 上传称重记录
         * task  任务信息
         *
         * @param context
         * @param listener 回调接口
         */
        private void updateFormulaInfo(Context context, final FormulaOkHttpListener listener,
                                       final CallBack back)
        {
            String handlerValue = getLocationToken(context);
            while (isSafety)
            {
                if (mUpLoadMultipleArrayList != null)
                {
                    if (mUpLoadMultipleArrayList.size() == 0)
                    {
                        continue;
                    }
                    if (!isSafety)
                    {
                        closeRun();
                        return;
                    }
                    FormulaMutilInvoiceInfo task = mUpLoadMultipleArrayList.get(0);
                    mUpLoadMultipleArrayList.remove(task);
                    if (task == null)
                    {
                        closeRun();
                        return;
                    }
                    if (mDecimalFormat == null) {
                        mDecimalFormat = new DecimalFormat();
                    }
                    WeightFormat.updateFormat(mDecimalFormat,task.getDecimalsNum());
                    RequestBody build = new FormEncodingBuilder()
                            .add(FormulaMutilHttpManager.IDKey, task.getID())
                            .add(FormulaMutilHttpManager.DeviceKey, task.getDevice())
                            .add(FormulaMutilHttpManager.TitleKey, task.getTitle())
                            .add(FormulaMutilHttpManager.MaxRangeKey, String.valueOf(task.getMaxRange()))
                            .add(FormulaMutilHttpManager.PrecisionKey, String.valueOf(task.getPrecision()))
                            .add(FormulaMutilHttpManager.TeamKey, task.getTeam())
                            .add(FormulaMutilHttpManager.IPAddressKey, task.getIPAddress())
                            .add(FormulaMutilHttpManager.PercentKey, String.valueOf(task.getPercent()))

                            .add(FormulaMutilHttpManager.MissionIDKey, task.getMissionID())
                            .add(FormulaMutilHttpManager.MissionDetailIDKey, task.getMissionDetailID())
                            .add(FormulaMutilHttpManager.WeightKey, mDecimalFormat.format(task.getWeight()))
                            .add(FormulaMutilHttpManager.DeviationWeightKey, String.valueOf(task.getDeviationWeight()))
                            .add(FormulaMutilHttpManager.SaltKey, task.getSalt())
                            .build();

                    URL_MULTIPLE_UPDATE_FORMULA = URL_MULTIPLE_REGISTGER_FORMULA + "/" + task.getID() + TASKS;
                    final Request request = new Request
                            .Builder()
                            .url(URL_MULTIPLE_UPDATE_FORMULA)
                            .addHeader(AUTHORIZATION, handlerValue)
                            .post(build)
                            .build();

                    if (mUpLoadMultipleArrayList != null)
                        mCall = mOkHttpClient.newCall(request);
                    mCall.enqueue(new Callback()
                    {
                        @Override
                        public void onFailure(Request request, IOException e)
                        {
                            back.onCallback(555, e.getMessage());
                            listener.onError(request, e);
                            isSafety = false;
                        }

                        @Override
                        public void onResponse(Response response) throws IOException
                        {
                            String s = "";
                            if (response != null)
                            {
                                int code = response.code();
                                if (null != listener)
                                {
                                    switch (code)
                                    {
                                        case HttpURLConnection.HTTP_BAD_REQUEST:
                                            listener.onError(response.request(), null);
                                            break;
                                        case HttpURLConnection.HTTP_OK:
                                            ResponseBody body = response.body();
                                            if (body != null)
                                                s = body.string();
                                            listener.onResponse(s, null, null);
                                            break;
                                        case HttpURLConnection.HTTP_NOT_FOUND:
                                            listener.onError(response.request(), null);
                                            break;
                                        default:
                                            listener.onError(response.request(), null);
                                            break;
                                    }
                                }
                                back.onCallback(code, s);
                            }
                            isSafety = false;
//                                    Back.callback();
                        }
                    });
                }
            }
        }
    }

    /**
     * 更新多台状态
     *
     * @param list
     * @param context
     * @param listener
     * @param uploadMultipleListener
     */
    public void changeMultiState(ArrayList list, Context context,
                                 final FormulaOkHttpListener listener, IUploadMultipleListener uploadMultipleListener)
    {
        if (mChangeMultiState != null)
        {
            mChangeMultiState.closeRun();
            mChangeMultiState = null;
        }
        if(list == null)
        {
            return;
        }
        mChangeMultiState = new ChangeMultiState(list, context, listener, uploadMultipleListener);
        if (!mChangeMultiState.isAlive())
            mChangeMultiState.start();
    }

    /**
     *
     */
    private class ChangeMultiState extends Thread
    {
        private ArrayList mList;
        private Context mContext;
        private FormulaOkHttpListener mListener;
        private IUploadMultipleListener mUploadMultipleListener;
        private boolean isSafety;
        private LinkedBlockingDeque mSendMsgQuene;
        private Call mCall;
        private OkHttpClient mOkHttpClient;
        private ArrayList mUpLoadMultipleArrayList;
        private ArrayList successList;
        private ArrayList errorList;

        /**
         * @param list
         * @param context
         * @param listener
         * @param uploadMultipleListener
         */
        ChangeMultiState(ArrayList list, Context context,
                         final FormulaOkHttpListener listener, IUploadMultipleListener uploadMultipleListener)
        {
//            mList = list;
            mList = new ArrayList();
            mList.addAll(list);
            mContext = context;
            mListener = listener;
            mUploadMultipleListener = uploadMultipleListener;
            isFlag = true;
            isSafety = true;
            mSendMsgQuene = new LinkedBlockingDeque();
            mOkHttpClient = new OkHttpClient();
            mUpLoadMultipleArrayList = new ArrayList();
            successList = new ArrayList();
            errorList = new ArrayList();
        }

        @Override
        public void run()
        {
            super.run();
            try {
                updateChangeInfo(mList, mContext, mListener, mUploadMultipleListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void closeRun()
        {
            isSafety = false;
            if (mList != null)
                mList.clear();
            if (mUpLoadMultipleArrayList != null)
                mUpLoadMultipleArrayList.clear();
            if (successList != null)
                successList.clear();
            if (errorList != null)
                errorList.clear();
            mList = null;
            mUpLoadMultipleArrayList = null;
            successList = null;
            errorList = null;
            mListener = null;
            mContext = null;
            mOkHttpClient = null;

        }

        /**
         * @param list     多个配料上传list
         * @param context
         * @param listener 回调
         */
        void updateChangeInfo(ArrayList list, Context context,
                        final FormulaOkHttpListener listener, IUploadMultipleListener uploadMultipleListener)
        {

            for (FormulaMulitTasks formulaUpLoadMultiple : list)
            {
                putQuene(formulaUpLoadMultiple);
                updateStateFormulaInfo(context, listener, new CallBack()
                {
                    @Override
                    public void onCallback(int start, String resualt)
                    {
                        switch (start)
                        {
                            case HttpURLConnection.HTTP_BAD_REQUEST:
//                                errorList.add(HttpURLConnection.HTTP_BAD_REQUEST);
                                break;
                            case HttpURLConnection.HTTP_OK:
                                Gson gson = new Gson();
                                FormulaMulitTasks result = gson.fromJson(resualt, new TypeToken()
                                {
                                }.getType());
//                                successList.add(result);
//
                                break;
                            case HttpURLConnection.HTTP_NOT_FOUND:
//                                errorList.add(HttpURLConnection.HTTP_NOT_FOUND);
                                break;

                            case 555:
//                                errorList.add(555);
                                break;
                        }
                    }
                });
            }
            if (uploadMultipleListener != null)
                uploadMultipleListener.onStatus(successList, errorList);
        }

        private void putQuene(FormulaMulitTasks formulaUpLoadMultiple)
        {
            isSafety = true;
            if (mUpLoadMultipleArrayList != null)
            {
                mUpLoadMultipleArrayList.add(formulaUpLoadMultiple);
            }
        }

        /**
         * 改变状态方法
         * task  任务信息
         *
         * @param context
         * @param listener 回调接口
         */
        private void updateStateFormulaInfo(Context context, final FormulaOkHttpListener listener,
                                       final CallBack back)
        {
            String handlerValue = getLocationToken(context);
            while (isSafety)
            {
                if (mUpLoadMultipleArrayList != null)
                {
                    if (mUpLoadMultipleArrayList.size() == 0)
                    {
                        continue;
                    }
                    if (!isSafety)
                    {
                        closeRun();
                        return;
                    }
                    FormulaMulitTasks task = mUpLoadMultipleArrayList.get(0);
                    mUpLoadMultipleArrayList.remove(task);
                    if (task == null)
                    {
                        closeRun();
                        return;
                    }
                    RequestBody build = new FormEncodingBuilder()
                            .add(FormulaMutilHttpManager.IDKey, task.getID())
                            .add(FormulaMutilHttpManager.DeviceKey, task.getDevice())
                            .add(FormulaMutilHttpManager.TitleKey, task.getTitle())
                            .add(FormulaMutilHttpManager.MaxRangeKey, String.valueOf(task.getMaxRange()))
                            .add(FormulaMutilHttpManager.PrecisionKey, String.valueOf(task.getPrecision()))
                            .add(FormulaMutilHttpManager.TeamKey, task.getTeam())
                            .add(FormulaMutilHttpManager.IPAddressKey, task.getIPAddress())
                            .add(FormulaMutilHttpManager.PercentKey, String.valueOf(task.getPercent()))

                            .add(FormulaMutilHttpManager.MissionIDKey, task.getMissionID())
                            .add(FormulaMutilHttpManager.MissionDetailIDKey, task.getMissionDetailID())
                            .add(FormulaMutilHttpManager.WeightKey, String.valueOf(task.getWeight()))
                            .add(FormulaMutilHttpManager.DeviationWeightKey, String.valueOf(task.getDeviationWeight()))
                            .add(FormulaMutilHttpManager.MaterialTitleKey, task.getMaterialTitle())
                            .add(FormulaMutilHttpManager.RecipeIDKey, task.getRecipeID())
                            .add(FormulaMutilHttpManager.LastHeartBeatKey, task.getLastHeartBeat())
                            .add(FormulaMutilHttpManager.StatusKey, String.valueOf(task.getStatus()))
                            .add(FormulaMutilHttpManager.StatusTitleKey, task.getStatusTitle())
                            .add(FormulaMutilHttpManager.MissionetailKey, task.getMissionDetail() + "")
                            .add(FormulaMutilHttpManager.SaltKey, task.getSalt())
                            .build();

                    URL_MULTIPLE_UPDATE_FORMULA = URL_MULTIPLE_REGISTGER_FORMULA + "/" + task.getID() + TASKS;
                    final Request request = new Request
                            .Builder()
                            .url(URL_MULTIPLE_UPDATE_FORMULA)
                            .addHeader(AUTHORIZATION, handlerValue)
                            .post(build)
                            .build();

                    if (mUpLoadMultipleArrayList != null)
                        mCall = mOkHttpClient.newCall(request);
                    mCall.enqueue(new Callback()
                    {
                        @Override
                        public void onFailure(Request request, IOException e)
                        {
//                        if(e.getCause().equals(SocketTimeoutException.class))//如果超时
                            back.onCallback(555, e.getMessage());
                            listener.onError(request, e);
//                                    Back.callback();
                            isSafety = false;
                        }

                        @Override
                        public void onResponse(Response response) throws IOException
                        {
                            String s = "";
                            Globals.log("sendHeartForFormulaMutil 5"+response);
                            if (response != null)
                            {
                                int code = response.code();
                                if (null != listener)
                                {
                                    switch (code)
                                    {
                                        case HttpURLConnection.HTTP_BAD_REQUEST:
                                            listener.onError(response.request(), null);
                                            break;
                                        case HttpURLConnection.HTTP_OK:
                                            ResponseBody body = response.body();
                                            if (body != null)
                                                s = body.string();
                                            listener.onResponse(s, null, null);
                                            break;
                                        case HttpURLConnection.HTTP_NOT_FOUND:
                                            listener.onError(response.request(), null);
                                            break;
                                        default:
                                            listener.onError(response.request(), null);
                                            break;
                                    }
                                }
                                    back.onCallback(code, s);
                            }
                            isSafety = false;
                        }
                    });
                    Globals.log("0 registerDeviceInfoListen 结束");
                }
            }
            Globals.log("1 registerDeviceInfoListen 结束");
        }
    }

    public interface CallBack
    {
        void onCallback(int start, String result);
    }

}
 
  
接口
/**
 * Created by lihengwei on 2016/3/31.
 */
public abstract class FormulaOkHttpListener<T>
{
    public void onError(Request request, Exception e)
    {
        // TODO: 2016/3/31
//        对一些系统错误进行统一操作,并释放接口
        onResponse(null, request, e);
    }

    public abstract void onResponse(T response, Request request, Exception e);

}

你可能感兴趣的:(Android---,笔记)