一些封装的工具类:
Posted 梦想家哈儿和他的bug
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一些封装的工具类:相关的知识,希望对你有一定的参考价值。
✈️一些封装的工具类:
最近:
好久没更新过CSDN了,在忙一些东西。每天的生活感觉枯燥又无趣哦,每天早上8.00左右来实验室,中午吃饭,下午吃饭,晚上10.00再回寝室,我像被程序控制着的一样,机械的行尸。每天雷打不动的两小时算法,复习计网和操作系统,再看看安卓的源码,再补补java的一些知识,倒是也蛮充足的。
闲言碎语
努努力拼一把吧,做好该做的事情,并接受它的事与愿违。但行好事莫问前程。
不说闲话了,写项目整理了不少工具类,今天就整理一下,以后用起来方便。
1️⃣ 提示框管理类:
提示框管理类里边实现了自定义提示框的显示,隐藏,初始化等。
代码:
/**
* FileName: DialogManager
* Profile: 提示框管理类
*/
public class DialogManager
private static volatile DialogManager mInstance = null;
private DialogManager()
public static DialogManager getInstance()
if (mInstance == null)
synchronized (DialogManager.class)
if (mInstance == null)
mInstance = new DialogManager();
return mInstance;
public DialogView initView(Context mContext, int layout)
return new DialogView(mContext, layout, R.style.Theme_Dialog, Gravity.CENTER);
public DialogView initView(Context mContext, int layout, int gravity)
return new DialogView(mContext, layout, R.style.Theme_Dialog, gravity);
public void show(DialogView view)
if (view != null)
if (!view.isShowing())
view.show();
public void hide(DialogView view)
if (view != null)
if (view.isShowing())
view.dismiss();
自定义提示框:
/**
* FileName: DialogView
* Profile: 自定义提示框
*/
public class DialogView extends Dialog
public DialogView(Context mContext, int layout, int style, int gravity)
super(mContext, style);
setContentView(layout);
Window window = getWindow();
WindowManager.LayoutParams layoutParams = window.getAttributes();
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
layoutParams.gravity = gravity;
window.setAttributes(layoutParams);
使用:
- 实例化自定义提示框;
- 通过提示框管理类将其初始化;
- 根据个人逻辑实现显示隐藏。
伪代码:
1. private DialogView mNullDialogView; //声明自定义提示框;
//通过管理类提供的方法将其实例化;
2. mNullDialogView = DialogManager.getInstance().initView(getActivity(), R.layout.layout_star_null_item, Gravity.BOTTOM);
//根据你所需的逻辑来控制其显示和隐藏
3. DialogManager.getInstance().show(mNullDialogView);
2️⃣网络框架OKHttp管理类:
代码:
/**
* @author 韩世凯
* @create 2021.8.10
* 对OKHttp网络框架进行了封装,使用起来比较方便
*/
public class Api
private static OkHttpClient client;
private static String requestUrl;
private static HashMap<String, Object> mParams;
public static Api api = new Api();
public Api()
/*get请求拼接参数*/
public static Api config(String url, HashMap<String, Object> params)
client = new OkHttpClient.Builder()
.build();
requestUrl = ApiConfig.BASE_URl + url;
mParams = params;
return api;
public void postRequest(Context context, final ITCallback callback)
SharedPreferences sp = context.getSharedPreferences("sp_it", MODE_PRIVATE);
String token = sp.getString("token", "");
JSONObject jsonObject = new JSONObject(mParams);
String jsonStr = jsonObject.toString();
RequestBody requestBodyJson =
RequestBody.create(MediaType.parse("application/json;charset=utf-8")
, jsonStr);
//第三步创建Rquest
Request request = new Request.Builder()
.url(requestUrl)
.addHeader("contentType", "application/json;charset=UTF-8")
.addHeader("token", token)
.post(requestBodyJson)
.build();
//第四步创建call回调对象
final Call call = client.newCall(request);
//第五步发起请求
call.enqueue(new Callback()
@Override
public void onFailure(Call call, IOException e)
Log.e("onFailure", e.getMessage());
callback.onFailure(e);
@Override
public void onResponse(Call call, Response response) throws IOException
final String result = response.body().string();
callback.onSuccess(result);
);
public void getRequest(Context context, final ITCallback callback)
SharedPreferences sp = context.getSharedPreferences("sp_it", MODE_PRIVATE);
String token = sp.getString("token", "");
String url = getAppendUrl(requestUrl, mParams);
Request request = new Request.Builder()
.url(url)
.addHeader("token", token)
.get()
.build();
Call call = client.newCall(request);
call.enqueue(new Callback()
@Override
public void onFailure(Call call, IOException e)
Log.e("onFailure", e.getMessage());
callback.onFailure(e);
@Override
public void onResponse(Call call, Response response) throws IOException
final String result = response.body().string();
try
JSONObject jsonObject = new JSONObject(result);
String code = jsonObject.getString("code");
if (code.equals("401"))
Intent in = new Intent(context, LoginActivity.class);
context.startActivity(in);
catch (JSONException e)
e.printStackTrace();
callback.onSuccess(result);
);
public void getRequestNew(Context context, final ITCallback callback)
SharedPreferences sp = context.getSharedPreferences("sp_it", MODE_PRIVATE);
String token = sp.getString("token", "");
String url = "http://122.9.144.12:8080/record/api/trainingRecordDetail/"+mParams.get("recordId");
Request request = new Request.Builder()
.url(url)
.addHeader("token", token)
.get()
.build();
Call call = client.newCall(request);
call.enqueue(new Callback()
@Override
public void onFailure(Call call, IOException e)
Log.e("onFailure", e.getMessage());
callback.onFailure(e);
@Override
public void onResponse(Call call, Response response) throws IOException
final String result = response.body().string();
try
JSONObject jsonObject = new JSONObject(result);
String code = jsonObject.getString("code");
if (code.equals("401"))
Intent in = new Intent(context, LoginActivity.class);
context.startActivity(in);
catch (JSONException e)
e.printStackTrace();
callback.onSuccess(result);
);
/*拼接参数,返回正确的URL*/
private String getAppendUrl(String url, Map<String, Object> map)
if (map != null && !map.isEmpty())
StringBuffer buffer = new StringBuffer();
Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext())
Map.Entry<String, Object> entry = iterator.next();
if (StringUtils.isEmpty(buffer.toString()))
buffer.append("?");
else
buffer.append("&");
buffer.append(entry.getKey()).append("=").append(entry.getValue());
url += buffer.toString();
return url;
和这个管理类配合使用的还需要实现一个接口:
public interface ITCallback
void onSuccess(String res);
void onFailure(Exception e);
使用:
这里举我项目中获取记录界面数据的一个请求函数:
/*获取记录界面的数据展示*/
public void getHFRecordList(final boolean isRefresh)
HashMap<String, Object> params = new HashMap<>();
params.put("pageSize", ApiConfig.LISTSIZE);
params.put("pageNum", listNum);
Api.config(ApiConfig.HFRECORDLIST, params).postRequest(getActivity(), new ITCallback()
@Override
public void onSuccess(final String res)
if (isRefresh)
refreshLayout.finishRefresh(true);
else
refreshLayout.finishLoadMore(true);
HFRecordShowResponse response = new Gson().fromJson(res, HFRecordShowResponse.class);
if (response != null && response.getMeta().getCode() == HttpURLConnection.HTTP_OK)
List<HFChildListResponse> list = response.getData().getRecordList().getList();
Log.d(TAG, "List.size---->"+list.size());
if (list != null && list.size() > 0)
if (isRefresh)
datas = list;
else
datas.addAll(list);
mHandler.sendEmptyMessage(0);
else
if (isRefresh)
showToastSync("暂时无数据");
else
showToastSync("没有更多数据");
@Override
public void onFailure(Exception e)
if (isRefresh)
refreshLayout.finishRefresh(true);
else
refreshLayout.finishLoadMore(true);
);
3️⃣ 地图管理类:
里边主要是项目里边使用高德地图的一些管理方法:
包括地址转经纬度,经纬度转地址,正反编码,获取静态地图URL等等
代码:
/**
* FileName: MapManager
* Profile: 地图管理类
*/
public class MapManager
private static volatile MapManager mInstance = null;
private GeocodeSearch geocodeSearch;
private OnAddress2PoiGeocodeListener address2poi;
private OnPoi2AddressGeocodeListener poi2address;
private MapManager()
//单例模式创建实例
public static MapManager getInstance()
if (mInstance == null)
synchronized (MapManager.class)
if (mInstance == null)
mInstance = new Android 工具类 SharedPreferences 封装