开发那点事(九)安卓开发,封装常用方法,工作用

开发背景
思路来源于开发那点事(八)在js的基础上封装的一些功能,这次写了一个安卓项目,并封装了网络请求,加载对话框,等常用的一些方法
公用方法

  • 1 Common,LogUtil等工具类抽取
  • 2 ApiRequest中GET POST等方法的封装
  • 3 BaseActivity的抽取
  • 4 LoadDialog加载对话框实现

上干货

1 Common,LogUtil工具类抽取
Common类
单例模式,其中定义了网络请求接口中的前缀,调试模式开关,并适配多环境打包。

package com.base.config;

public class Common {
    private static Common common = null;
    public String buildTip = "test";// 版本控制  test测试  online上线
    public Boolean appDebug = true;// 为true时为调试模式 正常输出日志
    public String preUrl = "";

    /**
     * 单例模式
     *
     * @return
     */
    public static Common getInstance() {
        if (common == null) {
            common = new Common();
            //根据buildTip的值来确定相应的url前缀
            switch (common.buildTip) {
                case "test":
                    common.preUrl = "http://mclasstest.club/JkReport/api/v1.";//test环境接口url前缀
                    break;
                case "online":
                    common.preUrl = "https://mclasstest.club/JkReport/api/v1.";//online环境接口url前缀
                    break;
            }
        }

        return common;
    }

    private Common() {
    }
}

LogUtil类
单例模式,根据Common类中的appDebug来判断控制输出,抽取TAG值

package com.base.util;

import android.util.Log;

import com.base.config.Common;

public class LogUtil {
    private static LogUtil logUtil = null;
    private static String TAG = "";
    private Common common = Common.getInstance();

    private LogUtil() {

    }

    /**
     * 单例模式
     *
     * @param tag log对应的TAG值,一般为activity的类名
     * @return
     */
    public static LogUtil getInstance(String tag) {
        if (logUtil == null) {
            logUtil = new LogUtil();
        }
        TAG = tag;
        logUtil.log("初始化log输出成功");
        return logUtil;
    }

    /**
     * 判断调试模式,打印log值
     * @param content 输出的内容
     */
    public void log(String content) {
        if (common.appDebug) {
            Log.d(TAG, content);
        }
    }
}

2 ApiRequest中GET POST等方法的封装
ApiRequest
单例模式,引入Okhttp,Common中的preUrl与方法中的url形成完整的url,抽取相应的请求参数,定义接口回调,根据接口返回的内容将错误统一处理

package com.base.util;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

import com.base.config.Common;
import com.base.dialog.LoadDialog;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ApiRequest {
    private Common common = Common.getInstance();
    private Context context;
    private static ApiRequest apiRequest = null;
    private LogUtil logUtil;
    private static OkHttpClient okHttpClient;

    private ApiRequest() {
        okHttpClient = new OkHttpClient().newBuilder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS).build();
    }


    public static ApiRequest getInstance(Context context, LogUtil logUtil) {
        if (apiRequest == null) {
            apiRequest = new ApiRequest();
        }
        apiRequest.context = context;
        apiRequest.logUtil = logUtil;
        return apiRequest;
    }

    /**
     * post请求
     *
     * @param url     接口名
     * @param params  post参数
     * @param apiUtil 回调
     */
    public void post(String url, Map params, final ApiUtil apiUtil) {
        String realUrl = common.preUrl + url;
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : params.keySet()) {
            builder.add(key, params.get(key));
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();
        final LoadDialog loadDialog = new LoadDialog(apiRequest.context);
        final Handler mHandler = new Handler();
        loadDialog.show();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                loadDialog.dismiss();
                if (apiRequest.logUtil != null) {
                    logUtil.log("onFailure");
                }
                showToast("未知原因,请重试");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                loadDialog.dismiss();
                final String result = response.body().string();
                apiRequest.logUtil.log(result);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            final JSONObject res = new JSONObject(result);
                            int responseCode = res.getInt("responseCode");
                            //如果 接口中responseCode等于0,说明返回正常,执行回调
                            if (responseCode == 0) {
                                apiUtil.requestCallBack(res);
                                return;
                            }
                            //否则输出接口中定义的responseMessage错误信息
                            String responseMessage = res.getString("responseMessage");
                            showToast(responseMessage);

                        } catch (JSONException e) {
                            showToast("未知原因,请重试");
                        }
                    }
                });
            }
        });

    }

    /**
     * get请求
     *
     * @param url     接口名
     * @param params  get参数
     * @param apiUtil 回调
     */
    public void get(String url, Map params, final ApiUtil apiUtil) {
        String realUrl = common.preUrl + url;
        int i = 0;
        for (String key : params.keySet()) {
            if (i == 0) {
                realUrl = realUrl + "?" + key + "=" + params.get(key);
            } else {
                realUrl = realUrl + "&" + key + "=" + params.get(key);
            }
            i++;
        }
        apiRequest.logUtil.log(realUrl);

        final LoadDialog loadDialog = new LoadDialog(apiRequest.context);
        loadDialog.show();
        Request request = new Request.Builder()
                .url(realUrl)
                .build();
        Call call = okHttpClient.newCall(request);
        final Handler mHandler = new Handler();
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                loadDialog.dismiss();
                if (apiRequest.logUtil != null) {
                    logUtil.log("onFailure");
                }
                showToast("未知原因,请重试");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                loadDialog.dismiss();
                final String result = response.body().string();
                apiRequest.logUtil.log(result);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            final JSONObject res = new JSONObject(result);
                            int responseCode = res.getInt("responseCode");
                            //如果 接口中responseCode等于0,说明返回正常,执行回调
                            if (responseCode == 0) {
                                apiUtil.requestCallBack(res);
                                return;
                            }
                            //否则输出接口中定义的responseMessage错误信息
                            String responseMessage = res.getString("responseMessage");
                            showToast(responseMessage);

                        } catch (JSONException e) {
                            showToast("未知原因,请重试");
                        }
                    }
                });
            }
        });
    }

    public void login() {
    }

    public interface ApiUtil {
        public void requestCallBack(JSONObject result);
    }

    /**
     * 弹出响应对话框
     *
     * @param content 弹框提示内容
     */
    private void showToast(String content) {
        Toast.makeText(apiRequest.context, content, Toast.LENGTH_SHORT).show();
    }

    /**
     * 弹出长时间响应对话框
     *
     * @param content 弹框提示内容
     */
    private void showLongToast(String content) {
        Toast.makeText(apiRequest.context, content, Toast.LENGTH_LONG).show();
    }
}

3 BaseActivity的抽取
BaseActivity
所有Activty的基类,抽取相关的方法

package com.base.base;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.base.util.ApiRequest;
import com.base.util.LogUtil;

public abstract class BaseActivity extends Activity {
    protected LogUtil logUtil;
    protected ApiRequest apiRequest;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        initData();
        initView();
        setListen();
    }

    /**
     * 初始化数据
     */
    public void initData() {
        logUtil = LogUtil.getInstance(getClass().getSimpleName());
        apiRequest = ApiRequest.getInstance(this, logUtil);
    }


    /**
     * @return 页面文件id
     */
    public abstract int getLayoutId();

    /**
     * 初始化页面组件
     */
    public abstract void initView();

    /**
     * 设置组件响应事件
     */
    public abstract void setListen();

    /**
     * 弹出响应对话框
     *
     * @param content 弹框提示内容
     */
    public void showToast(String content) {
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
    }

    /**
     * 弹出长时间响应对话框
     *
     * @param content 弹框提示内容
     */
    public void showLongToast(String content) {
        Toast.makeText(this, content, Toast.LENGTH_LONG).show();

    }
}

4 LoadDialog加载对话框实现
LoadDialog
继承自Dialog,在构造方法中自定义对话框样式,页面文件,添加imageView旋转动画
LoadDialog类

package com.base.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;

import com.base.R;

public class LoadDialog extends Dialog {
    public LoadDialog(@NonNull Context context) {
        super(context, R.style.loading_dialog);
        initView();
    }

    private void initView() {
        setContentView(R.layout.dialog_loading);
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.load_dialog);
        animation.setInterpolator(new LinearInterpolator());
        findViewById(R.id.loading_dialog_img).startAnimation(animation);
        setCanceledOnTouchOutside(true);
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.alpha = 0.8f;
        getWindow().setAttributes(attributes);
        setCancelable(false);
    }
}

anim文件



    


最后附上github地址,点我查看

你可能感兴趣的:(开发那点事(九)安卓开发,封装常用方法,工作用)