管灌系统巡查员智能手机App
zuoxiao
2024-09-24 45e69852f43abe0f79967786ada3c7cf887b5b48
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package com.dayu.pipirrapp.net;
 
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;
 
import com.dayu.pipirrapp.MyApplication;
import com.dayu.pipirrapp.bean.net.CodeResult;
import com.dayu.pipirrapp.bean.net.WeatherResponse;
import com.dayu.pipirrapp.net.subscribers.BaseProgressSubscriber;
import com.dayu.pipirrapp.net.subscribers.CodeListener;
import com.dayu.pipirrapp.net.subscribers.ProgressSubscriber;
import com.dayu.pipirrapp.net.subscribers.SubscriberListener;
import com.dayu.pipirrapp.utils.MapJpgUtils;
import com.dayu.pipirrapp.utils.MyJsonParser;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
 
 
/**
 * Copyright (C), 2023,
 * Author: zuot
 * Date: 2023-04-12 9:11
 * Description:
 */
public class ApiManager {
 
    static String TAG = "ApiManager";
 
    static ApiManager apiManager;
    //文件上传失败重复次数
    int uplodFilerepeatSize = 3;
 
    ApiService apiService;
    private CompositeDisposable compositeDisposable = new CompositeDisposable(); // 管理订阅事件
 
    /**
     * 初始化通信框架
     */
    public static void init() {
        if (apiManager == null) {
            apiManager = new ApiManager();
        }
    }
 
    public ApiManager() {
        apiService = RetrofitClient.getInstance().getApiService();
 
    }
 
    public static ApiManager getInstance() {
        return apiManager;
    }
 
 
    public <T> void requestPostLoading(final Context context, final String path, final Class<T> tClass, final Map<String, Object> params, final SubscriberListener listener) {
        request(context, false, path, false, tClass, params, listener);
    }
 
    public <T> void requestPostHideLoading(final Context context, final String path, final Class<T> tClass, final Map<String, Object> params, final SubscriberListener listener) {
        request(context, true, path, false, tClass, params, listener);
    }
 
    public <T> void requestPost(final Context context, final String path, final Class<T> tClass, final Map<String, Object> params, final SubscriberListener listener) {
        request(context, false, path, false, tClass, params, listener);
    }
 
    public <T> void requestGet(final Context context, final String path, final Class<T> tClass, final Map<String, Object> params, final SubscriberListener listener) {
        request(context, false, path, true, tClass, params, listener);
    }
 
    /**
     * 发送请求
     *
     * @param context
     * @param hideLoading 是否显示加载框  false:显示  true:隐藏
     * @param path        请求路径,在UrlConfig中定义
     * @param isGet       是否是Get请求 true:get 请求
     * @param tClass      对应的数据类型
     * @param params      Post请求时,对应的参数
     * @param listener    回调请求
     * @param <T>
     */
    public <T> void request(final Context context, final boolean hideLoading, final String path, final boolean isGet, final Class<T> tClass, final Map<String, Object> params, final SubscriberListener listener) {
        Observable observable;
        BaseProgressSubscriber<?> mySubscriber;
 
 
        if (isGet) {
            if (params == null) {
                observable = apiService.requestGet(path, MyApplication.myApplication.token);
            } else {
                observable = apiService.requestGet(path, params, MyApplication.myApplication.token);
            }
        } else {
            observable = apiService.requestPost(path, params);
        }
 
        mySubscriber = new ProgressSubscriber(context, hideLoading, listener);
        observable.subscribeOn(Schedulers.io()).
                map(new Function<Object, BaseResponse<T>>() {
                    @Override
                    public BaseResponse<T> apply(Object o) {
                        if (o instanceof BaseResponse) {
                            BaseResponse tem = (BaseResponse) o;
                            BaseResponse<T> response = new BaseResponse<>();
                            response.setCode(tem.getCode());
                            response.setMsg(tem.getMsg());
 
                            if (tClass != null) {
                                if (tem.getContent() instanceof Map) {
                                    response.setContent(parseMapContent(tem.getContent(), tClass));
                                } else if (tem.getContent() instanceof List) {
                                    response.setContent(parseListContent(tem.getContent(), tClass));
                                } else if (tem.getContent() instanceof Integer || tem.getContent() instanceof String) {
                                    response.setContent((T) tem.getContent());
                                }
                            }
                            return response;
                        }
 
                        return null;
                    }
                })
                .unsubscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mySubscriber);
 
    }
 
 
    // 解析 Map 类型的数据
    private <T> T parseMapContent(Object content, Class<T> tClass) {
        try {
            String jsonData = MyJsonParser.getJsontoMap((Map<String, Object>) content);
            return MyJsonParser.getBeanFromJson(jsonData, tClass);
        } catch (Exception e) {
            Log.e(TAG, "Error parsing map content", e);
            return null;
        }
    }
 
    // 解析 List 类型的数据
    private <T> T parseListContent(Object content, Class<T> tClass) {
        try {
            String jsonData = MyJsonParser.getJsonbyList((List<?>) content);
            return (T) MyJsonParser.getListByJson(jsonData, tClass);
        } catch (Exception e) {
            Log.e(TAG, "Error parsing list content", e);
            return null;
        }
    }
 
    /**
     * 获取天气
     *
     * @param data     经纬度(格式是 纬度:经度,英文冒号分隔)
     * @param callback
     * @param <T>
     */
    public <T> void requestWeather(String data, Callback<WeatherResponse> callback) {
        Map<String, Object> params = new HashMap<>();
        params.put("key", "S6Tq4pvOakMuWRrg0");
        params.put("location", data);
        params.put("language", "zh-Hans");
        params.put("unit", "c");
        params.put("days", "3");
        Call<WeatherResponse> call = apiService.requestWeather("https://api.seniverse.com/v3/weather/daily.json", params);
        call.enqueue(callback);
    }
 
 
    /**
     * 获取验证码
     *
     * @param params
     * @param listener
     * @param <T>
     */
    public <T> void getCode(Map<String, Object> params, CodeListener listener) {
        if (isNetworkAvailable(MyApplication.myApplication)) {
            Observable observable;
            observable = apiService.getCode(params);
            observable.subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(responseBody -> {
                        listener.onNext((CodeResult) responseBody);
                    }, throwable -> {
                        listener.error((Throwable) throwable);
                    });
        } else {
            listener.onNext(null);
        }
 
    }
 
 
    /**
     * 下载地图瓦片
     *
     * @param urlPath
     */
    public void donwLoadTile(String urlPath) {
        Observable<ResponseBody> observable;
        observable = apiService.downloadTile(urlPath);
 
 
//        compositeDisposable.add(
        observable
                .subscribeOn(Schedulers.io())  // 网络请求在 I/O 线程中进行
                .observeOn(Schedulers.io())    // 回调处理也在 I/O 线程
                .subscribe(
                        responseBody -> {
 
                            boolean success = false;
                            if (!MapJpgUtils.getInsatance().isHasFiles(urlPath)) {
                                success = MapJpgUtils.getInsatance().saveTileToCache(urlPath, responseBody);
                            }
                            if (success) {
                                Log.d(TAG, "Download success for tile: " + urlPath);
                            } else {
                                Log.e(TAG, "Failed to save tile to disk: " + urlPath);
                            }
                        },
                        throwable -> Log.e(TAG, "Download failed for tile: " + urlPath)
                );
//        );
 
 
    }
 
    // 停止线程池,释放资源
    public void clearDisposables() {
        if (!compositeDisposable.isDisposed()) {
            compositeDisposable.dispose();
        }
    }
 
    /**
     * 判断当前是否有网络
     *
     * @param context
     * @return
     */
    public boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
 
        if (connectivityManager != null) {
            // 对于 Android 版本大于等于 Android Q (API level 29)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
                if (capabilities != null) {
                    // 检查网络是否有传输能力(包括 Wi-Fi 和移动数据)
                    if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        return true;
                    }
                }
            } else {
                // 对于 Android Q 以下版本
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
                    return true;
                }
            }
        }
 
        return false;  // 无网络连接
    }
 
}