wjc
2023-06-06 5308d04e20f3dca6d56ccc3e2b460374540716a6
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package com.zxing;
 
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;
 
import com.zxing.utils.Strings;
import com.zxing.utils.Validator;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;
import java.util.Locale;
 
import static android.telephony.TelephonyManager.SIM_STATE_READY;
 
/**
 * 用途:取设备相关信息
 */
public class DeviceHelper {
 
    /**
     * 获取应用的版本号
     */
    public static String getAppVersion() {
        Context context = ContextHelper.getAppContext();
        if (context != null) {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo;
            try {
                packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                return packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return Strings.EMPTY;
    }
 
    public static void ClipData(String content) {
        ClipboardManager cm = (ClipboardManager) ContextHelper.getAppContext().getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        if (cm != null) {
            cm.setText(content);
        }
    }
 
    /**
     * 启动应用的设置
     */
    public static void startAppSettings(Activity activity, int requestCode) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        activity.startActivityForResult(intent, requestCode);
    }
 
    /**
     * 获取版本信息 versioncode
     */
    public static int getVersionCode() {
        final Context context = ContextHelper.getAppContext();
        int version = 1;
        if (context != null) {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = null;
            try {
                packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (packInfo != null) {
                version = packInfo.versionCode;
            }
        }
        return version;
    }
 
    /**
     * 获取设备的制造商
     */
    public static String getFactory() {
        return Build.MANUFACTURER;
    }
 
    /**
     * 获取系统版本号
     */
    public static String getPhoneOS() {
        return "Android " + getSysVersion() + " " + Build.VERSION.RELEASE;
    }
 
    /**
     * 版本是否在Android6.0 以上
     */
    public static boolean isOverMarshmallow() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }
 
    /**
     * 获取Android API版本
     */
    public static String getSysVersion() {
        return Build.VERSION.SDK_INT + Strings.EMPTY;
    }
 
    /**
     * 获取Android API版本
     */
    public static int getSysVersionInt() {
        return Build.VERSION.SDK_INT;
    }
 
    /**
     * 获取手机型号
     */
    public static String getPhoneModel() {
        String model = Build.BRAND + " " + Build.MODEL;
        if (!TextUtils.isEmpty(model) && model.length() > 50) {
            model = model.substring(0, 49);
        }
        return Validator.replaceHanzi(model);
    }
 
    /**
     * 判断IMEI是否为纯数字串
     */
    private static boolean isNumber(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        boolean isNumber = true;
        int i;
        char c;
        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            if (!((c >= '0') && (c <= '9')) || "000000000000000".equals(str) || "0".equals(str)) {
                isNumber = false;
                break;
            }
        }
        return isNumber;
    }
 
    private static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }
 
    private static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }
 
    /**
     * 判断mac地址是否合法
     */
    private static boolean isCorrectMacAddress(String address) {
        boolean flag = false;
        if (!TextUtils.isEmpty(address) && address.length() == 17) {
            address = address.replaceAll(":", Strings.EMPTY);
            flag = isHex(address);
        }
        return flag;
    }
 
    /**
     * 判断是否为纯16进制数字串
     */
    private static boolean isHex(String str) {
        boolean isHexFlg = true;
        int i;
        char c;
        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            if (!(((c >= '0') && (c <= '9')) ||
                    ((c >= 'A') && (c <= 'F')) ||
                    (c >= 'a') && (c <= 'f'))) {
                isHexFlg = false;
                break;
            }
        }
        return isHexFlg;
    }
 
    /**
     * 判断系统中是否存在可以启动的相机应用
     *
     * @return 存在返回true,不存在返回false
     */
    public static boolean hasCamera(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }
 
 
    /**
     * 检测系统是否为MIUI
     */
    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
 
    /**
     * 获取渠道
     */
    public static String getChannel() {
        return "";
    }
 
    /**
     * 获取手机宽高
     */
    public static String getPhonePixels(Activity activity) {
        if (activity != null) {
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            int widthPixels = dm.widthPixels;
            int heightPixels = dm.heightPixels;
            return widthPixels + "-" + heightPixels;
        }
        return "0-0";
    }
 
    /**
     * x
     * 屏幕宽度
     */
    public static int getDeviceWidth(Context context) {
        if (context != null) {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            if (wm != null) {
                Point p = new Point();
                wm.getDefaultDisplay().getSize(p);
                return p.x;
            }
        }
        return 0;
    }
 
    /**
     * 屏幕宽度
     */
    public static int getDeviceWidth(Activity activity) {
        if (activity != null) {
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            return dm.widthPixels;
        }
        return 0;
    }
 
    /**
     * 屏幕高度
     */
    public static int getDeviceHeight(Activity activity) {
        if (activity != null) {
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            return dm.heightPixels;
        }
        return 0;
    }
 
 
    /**
     * 判断当前有没有网络连接
     */
    public static boolean getNetworkState() {
        Context context = ContextHelper.getAppContext();
        if (context != null) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkinfo = manager.getActiveNetworkInfo();
            return !(networkinfo == null || !networkinfo.isAvailable());
        }
        return false;
    }
 
    /**
     * SD卡是否挂载
     */
    public static boolean mountedSdCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }
 
    /**
     * 检测应用是否安装
     **/
    public static boolean isApkInstalled(String packageName) {
        Context context = ContextHelper.getAppContext();
        if (context != null) {
            final PackageManager packageManager = context.getPackageManager();
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
            for (int i = 0; i < pinfo.size(); i++) {
                if (pinfo.get(i).packageName.equalsIgnoreCase(packageName)) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }
 
    /**
     * 打电话
     */
    public static void callPhone(Activity activity, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }
 
    /**
     * 调用系统发送短信
     */
    public static void sendSMSView(Activity activity, String phone, String sms) {
        Uri smsToUri = Uri.parse("smsto:" + phone);
        Intent sendIntent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        sendIntent.putExtra("sms_body", sms);
        activity.startActivity(sendIntent);
    }
 
    private static TelephonyManager getTelManager() {
        Context context = ContextHelper.getAppContext();
        if (context == null) {
            return null;
        }
        return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    }
 
    /**
     * 获取ISO国家码,相当于提供SIM卡的国家码
     */
    public static String getSimCountryIso() {
        if (getTelManager() != null) {
            return getTelManager().getSimCountryIso();
        }
 
        return Strings.EMPTY;
    }
 
    /**
     * 获取运营商名称
     */
    public static String getSimOperatorName() {
        if (getTelManager() != null && SIM_STATE_READY == getTelManager().getSimState()) {
            return getTelManager().getSimOperatorName();
        }
 
        return Strings.EMPTY;
    }
 
    /**
     * 获取系统运行内存大小 单位KB
     */
    public static long getTotalMemory() {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
 
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行,系统总内存大小
            if (TextUtils.isEmpty(str2)) {
                arrayOfString = str2.split("\\s+");
                initial_memory = Integer.valueOf(arrayOfString[1]);// 获得系统总内存,单位是KB
            }
            localBufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return initial_memory;// Byte转换为KB或者MB,内存大小规格化
    }
 
    /**
     * 设备语言编码
     */
    public static String getLanguage() {
        String language = Strings.EMPTY;
        Resources resources = ContextHelper.getResources();
        if (resources != null) {
            Locale locale = ContextHelper.getResources().getConfiguration().locale;
            language = locale.getLanguage();
        }
 
        return language;
    }
 
    /**
     * 获取机身总存储(不包含SD卡)
     */
    public static long getRomMemory() {
        long[] romInfo = new long[1];
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        //Total rom memory
        romInfo[0] = blockSize * totalBlocks;
        return romInfo[0];
    }
 
    /**
     * 获取CPU最大频率(单位KHZ)
     */
    public static String getMaxCpuFreq() {
        StringBuilder result = new StringBuilder(Strings.EMPTY);
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result.append(new String(re));
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = new StringBuilder("N/A");
        }
        return result.toString().trim();
    }
 
    /**
     * 是否取到所有信息
     */
    private static boolean isGetSuccess() {
        return !TextUtils.isEmpty(getPhoneModel()) && !TextUtils.isEmpty(getFactory())
                && !TextUtils.isEmpty(getMaxCpuFreq()) && getRomMemory() > 0 && getTotalMemory() > 0;
    }
}