Development background ideas from the development of that thing (eight) on the basis of JS package some functions, this time wrote an Android project, and encapsulate the network request, load dialog box, such as some common methods public method

  • 1. Common,LogUtil, etc
  • 2 Encapsulation of methods such as GET and POST in ApiRequest
  • 3 BaseActivity extraction
  • 4 LoadDialog Is implemented

On dry

1 Common, the LogUtil utility class extracts the Common class singleton pattern, which defines prefixes in the network request interface, debug mode switches, and ADAPTS to multi-environment packaging.

package com.base.config;

public class Common {
    private static Common common = null;
    public String buildTip = "test";// Version control test Test online goes online
    public Boolean appDebug = true;// Logs are generated in debug mode when the value is true
    public String preUrl = "";

    /** * singleton mode **@return* /
    public static Common getInstance(a) {
        if (common == null) {
            common = new Common();
            // Determine the corresponding URL prefix based on the buildTip value
            switch (common.buildTip) {
                case "test":
                    common.preUrl = "http://mclasstest.club/JkReport/api/v1.";//test Specifies the url prefix of the environment interface
                    break;
                case "online":
                    common.preUrl = "https://mclasstest.club/JkReport/api/v1.";//online The url prefix of the environment interface
                    break; }}return common;
    }

    private Common(a) {}}Copy the code

LogUtil class singleton mode, according to the Common class appDebug to judge the control output, extract the TAG value

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(a) {}/** * singleton mode **@paramTag Log Tag value, usually the activity class name *@return* /
    public static LogUtil getInstance(String tag) {
        if (logUtil == null) {
            logUtil = new LogUtil();
        }
        TAG = tag;
        logUtil.log("Initialization log output successful");
        return logUtil;
    }

    /** * Determine the debug mode and print the log value *@paramContent Output content */
    public void log(String content) {
        if(common.appDebug) { Log.d(TAG, content); }}}Copy the code

2. Encapsulation of methods like GET and POST in ApiRequest singleton mode, introduction of Okhttp, preUrl in Common and URL in method to form a complete URL, extraction of corresponding request parameters, definition of interface callback, and unified processing of errors according to the content returned by the interface

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(a) {
        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 request **@paramUrl Interface name *@paramParams Post parameter *@paramApiUtil callback * /
    public void post(String url, Map<String, String> 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("For unknown reason, please try again.");
            }

            @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(a) {
                        try {
                            final JSONObject res = new JSONObject(result);
                            int responseCode = res.getInt("responseCode");
                            // If the responseCode of the interface is 0, the responseCode is returned to normal and the callback is executed
                            if (responseCode == 0) {
                                apiUtil.requestCallBack(res);
                                return;
                            }
                            // otherwise output the responseMessage error message defined in the interface
                            String responseMessage = res.getString("responseMessage");
                            showToast(responseMessage);

                        } catch (JSONException e) {
                            showToast("For unknown reason, please try again."); }}}); }}); }/** * get request **@paramUrl Interface name *@paramParams get parameter *@paramApiUtil callback * /
    public void get(String url, Map<String, String> 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("For unknown reason, please try again.");
            }

            @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(a) {
                        try {
                            final JSONObject res = new JSONObject(result);
                            int responseCode = res.getInt("responseCode");
                            // If the responseCode of the interface is 0, the responseCode is returned to normal and the callback is executed
                            if (responseCode == 0) {
                                apiUtil.requestCallBack(res);
                                return;
                            }
                            // otherwise output the responseMessage error message defined in the interface
                            String responseMessage = res.getString("responseMessage");
                            showToast(responseMessage);

                        } catch (JSONException e) {
                            showToast("For unknown reason, please try again."); }}}); }}); }public void login(a) {}public interface ApiUtil {
        public void requestCallBack(JSONObject result);
    }

    /** * A response dialog box is displayed@paramContent Content displayed in the dialog box */
    private void showToast(String content) {
        Toast.makeText(apiRequest.context, content, Toast.LENGTH_SHORT).show();
    }

    /** * Displays a long response dialog box **@paramContent Content displayed in the dialog box */
    private void showLongToast(String content) { Toast.makeText(apiRequest.context, content, Toast.LENGTH_LONG).show(); }}Copy the code

3 BaseActivity extraction BaseActivity all Activty base class, extraction of related methods

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();
    }

    /** * Initializes data */
    public void initData(a) {
        logUtil = LogUtil.getInstance(getClass().getSimpleName());
        apiRequest = ApiRequest.getInstance(this, logUtil);
    }


    / * * *@returnPage file ID */
    public abstract int getLayoutId(a);

    /** * Initialize the page component */
    public abstract void initView(a);

    /** * sets the component to respond to events */
    public abstract void setListen(a);

    /** * A response dialog box is displayed@paramContent Content displayed in the dialog box */
    public void showToast(String content) {
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
    }

    /** * Displays a long response dialog box **@paramContent Content displayed in the dialog box */
    public void showLongToast(String content) {
        Toast.makeText(this, content, Toast.LENGTH_LONG).show(); }}Copy the code

LoadDialog inherit from Dialog, in the constructor custom Dialog box style, page file, add imageView rotation animation LoadDialog class

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(a) {
        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.8 f;
        getWindow().setAttributes(attributes);
        setCancelable(false); }}Copy the code

Anim file

<? xml version="1.0" encoding="utf-8"? > <set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate
        android:duration="1000"
        android:fromDegrees="0"
        android:interpolator="@android:anim/overshoot_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
         #repeatCount -1 means infinite execution of this animation. In this case, imageView loading box is in and out of rotation
        android:repeatCount="1" 
        android:repeatMode="restart"
        android:toDegrees="+ 360" />

</set>
Copy the code

Finally, attach the Github address, click me to view