当前位置 : 主页 > 编程语言 > java >

一个专为OkHttpUtils(via. zhy) 封装的网络接口回调类,提供了流量统计、网络错误

来源:互联网 收集:自由互联 发布时间:2021-06-28
一个专为OkHttpUtils(via. zhy) 封装的网络接口回调类,提供了流量统计、网络错误提示(含网络错误码)、加载窗(支持圆圈以及水平ProgressBar,水平的支持进度显示) import android.app.Acti
一个专为OkHttpUtils(via. zhy) 封装的网络接口回调类,提供了流量统计、网络错误提示(含网络错误码)、加载窗(支持圆圈以及水平ProgressBar,水平的支持进度显示)
import android.app.Activity;
import android.app.AlertDialog;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.zhy.http.okhttp.callback.Callback;

import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Locale;
import java.util.concurrent.TimeoutException;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by hp on 2017/9/19.
 * 带Toast提示的网络请求回调接口
 */
public abstract class TipStringCallback extends Callback
 
   {
    private Activity activity;
    private final String tag = "TipStringCallback --> ";
    private AlertDialog dialog;
    private TextView txtTip;
    private ProgressBar proBar;
    private ProgressBar proBarHorizontal;

    public TipStringCallback() {
    }

    /**
     * 用于获取Context实例,初始化Dialog,返回 {@code null} 不会有加载窗
     */
    public abstract Activity setInnerActivity();

    /**
     * 返回加载窗提示信息
     */
    public String getTipMessage() {
        return null;
    }

    @Override
    public void inProgress(float progress, long total, int id) {
        super.inProgress(progress, total, id);
        if (useProgressBarHorizontal() && proBarHorizontal != null) {
            proBarHorizontal.setProgress((int) (progress * 100));
        }
    }

    /**
     * 是否使用横向ProgressBar(带进度)
     */
    public boolean useProgressBarHorizontal() {
        return false;
    }

    @Override
    public void onBefore(Request request, int id) {
        super.onBefore(request, id);
        showDialog(true);
    }

    @Override
    public String parseNetworkResponse(Response response, int i) throws Exception {
        String re = response.body().string();
        if (BuildConfig.DEBUG) {
            long t = System.currentTimeMillis();
            LogUtil.i(tag, "resBytes=" + formatLengthReadable(re.getBytes().length) + ", 打印耗时: " + (System.currentTimeMillis() - t) + "ms");
        }
        return re;
    }

    @Override
    public void onError(Call call, Exception e, int i) {
        showDialog(false);

        //错误原因
        String tips = "";
        if (!NetUtils.isConnect(activity)) {
            tips += "网络未连接, ";
            toast("网络未连接,请检查您的网络", null);
        } else if (e instanceof UnknownHostException || e instanceof ConnectException) {
            toast("连接失败,请检查您的网络", null);
        } else if (e instanceof TimeoutException || e instanceof SocketTimeoutException) {
            toast("连接超时,请稍后重试", null);
        }
        tips += e.getMessage();

        if (call != null) {
            call.cancel();
        }

        LogUtil.e(tag, String.format(Locale.CHINESE, "onError: id=%d, %s, %s", i, tips, e == null ? "" : e.getMessage()));
    }

    @Override
    public boolean validateReponse(Response response, int id) {
        showDialog(false);

        // 错误原因
        String tips = "";
        if (response.code() >= 500 && response.code() < 600) {
            tips = "服务器错误";
            toast(tips, response);
        }
        if (response.code() >= 400 && response.code() < 500) {
            tips = "请求错误";
            toast(tips, response);
        }

        LogUtil.e(tag, tips + ": " + response.toString());

        return super.validateReponse(response, id);
    }

    private void initDialog() {
        if (activity == null) {
            activity = setInnerActivity();
        }
        if (activity != null) {
            if (dialog == null) {
                try {
                    View v = View.inflate(activity, R.layout.dialog_loading, null);
                    if (useProgressBarHorizontal()) {
                        proBarHorizontal = (ProgressBar) v.findViewById(R.id.dialog_loading_progress_horizontal);
                        proBarHorizontal.setVisibility(View.VISIBLE);
                        if (proBar != null) proBar.setVisibility(View.INVISIBLE);
                    } else {
                        proBar = (ProgressBar) v.findViewById(R.id.dialog_loading_progress);
                        proBar.setVisibility(View.VISIBLE);
                        if (proBarHorizontal != null)
                            proBarHorizontal.setVisibility(View.INVISIBLE);
                    }
                    txtTip = (TextView) v.findViewById(R.id.dialog_loading_txt_tips);
                    dialog = new AlertDialog.Builder(activity).setView(v).create();
                } catch (Exception e) {
                    LogUtil.e(tag, "提示用Dialog初始化失败", e);
                }
            }
        } else {
            dialog = null;
        }
    }

    private void showDialog(boolean show) {
        initDialog();
        if (show) {
            if (dialog != null && !dialog.isShowing()) {
                if (!TextUtils.isEmpty(getTipMessage()) && txtTip != null) {
                    txtTip.setText(getTipMessage());
                }
                dialog.show();
            }
        } else {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    private void toast(@NonNull String text, @Nullable Response response) {
        if (activity != null) {
            activity.runOnUiThread(new ToastRunnable(text, response));
        }
    }

    private class ToastRunnable implements Runnable {
        private String tip;
        private Response response;

        ToastRunnable(String tip, Response response) {
            this.tip = tip;
            this.response = response;
        }

        @Override
        public void run() {
            if (activity != null) {
                if (response != null) {
                    Toast.makeText(activity, tip + "(" + response.code() + ")", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(activity, tip, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private String formatLengthReadable(double length) {
        String[] units = new String[]{"B", "KB", "MB", "GB", "TB", "PB"};
        double mod = 1024.0;
        int i = 0;
        for (i = 0; length >= mod; i++) {
            length /= mod;
            if (i >= units.length - 1) {
                break;
            }
        }
        try {
            BigDecimal a = new BigDecimal(length);

            return a.setScale(2, BigDecimal.ROUND_HALF_UP) + units[i];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return length + units[i];
    }
}
 
加载窗布局文件
 

 

    
  

    
  

    
  


 
水平ProgressBar自定义的渐变背景
上一篇:Predicate
下一篇:Android 禁止截屏
网友评论