Linjiajia
2023-12-29 590c1cff46b105d774271f950caa9f65523f05c1
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package com.android.app_base.utils;
 
import android.animation.ValueAnimator;
import android.app.ActionBar;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
 
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
 
import com.android.app_base.base.BaseApplication;
import com.blankj.utilcode.util.LogUtils;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
 
/**
 * @author Ljj
 * @date 2023.05.18. 19:29
 * @desc
 */
public class Utils {
    /**
     * 下拉展开
     * @param view 需要展开的view
     * @param initialHeight 初始高度
     * @param targetHeight 目标高度
     */
    public static void dropExpand(View view,int initialHeight , int targetHeight) {
        ValueAnimator animator = ValueAnimator.ofInt(initialHeight,targetHeight);
        animator.setDuration(400);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                view.getLayoutParams().height = value;
                view.requestLayout();
            }
        });
        animator.start();
    }
    /**
     * 上拉收起
     * @param view 需要收起的view
     * @param initialHeight 初始高度
     * @param targetHeight 目标高度
     */
    public static void pullCollapse(View view,int initialHeight, int targetHeight) {
        ValueAnimator animator = ValueAnimator.ofInt(initialHeight, targetHeight);
        animator.setDuration(400);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                view.getLayoutParams().height = value;
                view.requestLayout();
            }
        });
        animator.start();
    }
 
    /**
     * 判断点击的点是否在view内
     * @param x x坐标
     * @param y y坐标
     * @param view view
     * @return 是否在view内
     */
    public static boolean isPointInsideView(float x, float y, View view) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
 
        int left = location[0];
        int top = location[1];
        int right = left + view.getWidth();
        int bottom = top + view.getHeight();
 
        return x >= left && x <= right && y >= top && y <= bottom;
    }
 
    /**
     * 字符串转日期
     * @param dateString 日期字符串
     * @return 日期 Date
     */
    public static Date parseDate(String dateString) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault());
            return dateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     *  分割字符串成list
     */
    public static List<String> splitString2List(String str, String splitStr) {
        if (str == null|| TextUtils.isEmpty(str)){
            return new ArrayList<>();
        }
        String[] split = str.split(splitStr);
        List<String> list = new ArrayList<>();
        for (String s : split) {
            if (!TextUtils.isEmpty(s)){
                list.add(s);
            }
        }
        return list;
    }
 
    /**
     *  list拼接成字符串
     */
    public static String appendList2String(List<String> list,String appendStr) {
        if (list == null || list.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String s : list) {
            sb.append(s).append(appendStr);
        }
        //去掉最后一个拼接符
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - appendStr.length());
        }
        return sb.toString();
    }
 
    /**
     *  设置 TextView 文本溢出处理方式
     */
    public static void setTextViewEllipsize(TextView textView, TextUtils.TruncateAt where) {
        if (textView.getEllipsize() == where) {
            return;
        }
        textView.setEllipsize(where);
        if (where != TextUtils.TruncateAt.MARQUEE) {
            return;
        }
        if (!textView.isSelected()) {
            // 设置跑马灯之后需要设置选中才能有效果
            textView.setSelected(true);
        }
        if (!textView.isFocusable()) {
            // 设置跑马灯需要先获取焦点
            textView.setFocusable(true);
        }
        textView.setSingleLine(true);
        // 设置跑马灯的循环次数
        textView.setMarqueeRepeatLimit(-1);
    }
 
    /**
     *  判断两个日期大小
     */
    public static int compareDate(String startTime, String endTime) {
        //比较时间大小
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault());
        try {
            Date startDate = dateFormat.parse(startTime);
            Date endDate = dateFormat.parse(endTime);
            if (startDate == null || endDate == null) {
                return 0;
            }
            return startDate.compareTo(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
 
    /**
     *  计算两个日期相差天数
     */
    public static int calculateDays(String startTime, String endTime) {
        int days = 0;
        //计算两个日期相差天数
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault());
        try {
            Date startDate = dateFormat.parse(startTime);
            Date endDate = dateFormat.parse(endTime);
            if (startDate == null || endDate == null) {
                return 0;
            }
            days = (int) TimeUnit.DAYS.convert(Math.abs(startDate.getTime() - endDate.getTime()), TimeUnit.MILLISECONDS);
 
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return days + 1;
    }
 
    /**
     *  安装 APK
     */
    public static void installAPK(Context context, String fileName) {
        fileName = Environment.getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + fileName;
        LogUtils.e(fileName);
        File file = new File(fileName);
        if (!file.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".file-provider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
//            Uri uri = Uri.parse("file://" + file.toString());
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            //在服务中开启activity必须设置flag,后面解释
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }
 
    /**
     * 判断是否有网络
     */
    public static boolean checkNetwork() {
//        if (context == null) {
//            return false;
//        }
//        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//        if (mConnectivityManager == null) {
//            return false;
//        }
//        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
//        return mNetworkInfo != null && mNetworkInfo.isAvailable();
 
        Application application = BaseApplication.getInstance();
        if (application != null) {
            ConnectivityManager manager = ContextCompat.getSystemService(application, ConnectivityManager.class);
            if (manager != null) {
                NetworkInfo info = manager.getActiveNetworkInfo();
                // 判断网络是否连接
                if (info == null || !info.isConnected()) {
                    return false;
                }
            }
        }
        return true;
    }
 
    /**
     * 把 view 转换成 drawable
     */
    public static Drawable convertViewToDrawable(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        int width = view.getMeasuredWidth();
        int height = view.getMeasuredHeight();
 
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
 
        view.layout(0, 0, width, height);
        view.draw(canvas);
 
        return new BitmapDrawable(view.getResources(), bitmap);
    }
 
 
    /**
     * 计算文件的MD5哈希值
     *
     * @param file 文件
     * @return 文件的MD5哈希值,如果计算失败则返回null
     */
    public static String calculateMD5(File file) {
        try {
            // 获取MD5消息摘要算法的实例
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 创建文件URL
            // 打开文件输入流,并使用DigestInputStream更新消息摘要
            try (FileInputStream is = new FileInputStream(file);
                 DigestInputStream dis = new DigestInputStream(is, md)) {
                // 读取输入流并更新消息摘要
                byte[] buffer = new byte[1024*256];
                while(true){
                    if (!(dis.read(buffer) > 0)) break;
                }
                // 获取MD5哈希值的字节数组
                md = dis.getMessageDigest();
                byte[] mdBytes = md.digest();
                // 将字节数组转换为十六进制字符串
                StringBuilder hexString = new StringBuilder();
                for (byte mdByte : mdBytes) {
                    hexString.append(Integer.toHexString(0xFF & mdByte));
                }
                return hexString.toString();
            }
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}