服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android判断用户2G/3G/4G移动数据网络

Android判断用户2G/3G/4G移动数据网络

2021-04-25 14:46Android教程网 Android

这篇文章主要介绍了Android判断用户2G/3G/4G移动数据网络的方法,感兴趣的小伙伴们可以参考一下

在做 Android App 的时候,为了给用户省流量,为了不激起用户的愤怒,为了更好的用户体验,是需要根据用户当前网络情况来做一些调整的,也可以在 App 的设置模块里,让用户自己选择,在 2G / 3G / 4G 网络条件下,是否允许请求一些流量比较大的数据。

通过 Android 提供的 TelephonyManager 和 ConnectivityManager 都可以获取到 NetworksInfo 对象,可以通过 getType() 获取类型,判断是 wifi 还是 mobile ,如果是 mobile ,可以通过 NetworksInfo 对象的 getSubType() 和 getSubTypeName() 可以获取到对于的网络类型和名字。

网络类型和名字定义在 TelephonyManager 类里。

?
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
/** Network type is unknown */
public static final int NETWORK_TYPE_UNKNOWN = 0;
/** Current network is GPRS */
public static final int NETWORK_TYPE_GPRS = 1;
/** Current network is EDGE */
public static final int NETWORK_TYPE_EDGE = 2;
/** Current network is UMTS */
public static final int NETWORK_TYPE_UMTS = 3;
/** Current network is CDMA: Either IS95A or IS95B*/
public static final int NETWORK_TYPE_CDMA = 4;
/** Current network is EVDO revision 0*/
public static final int NETWORK_TYPE_EVDO_0 = 5;
/** Current network is EVDO revision A*/
public static final int NETWORK_TYPE_EVDO_A = 6;
/** Current network is 1xRTT*/
public static final int NETWORK_TYPE_1xRTT = 7;
/** Current network is HSDPA */
public static final int NETWORK_TYPE_HSDPA = 8;
/** Current network is HSUPA */
public static final int NETWORK_TYPE_HSUPA = 9;
/** Current network is HSPA */
public static final int NETWORK_TYPE_HSPA = 10;
/** Current network is iDen */
public static final int NETWORK_TYPE_IDEN = 11;
/** Current network is EVDO revision B*/
public static final int NETWORK_TYPE_EVDO_B = 12;
/** Current network is LTE */
public static final int NETWORK_TYPE_LTE = 13;
/** Current network is eHRPD */
public static final int NETWORK_TYPE_EHRPD = 14;
/** Current network is HSPA+ */
public static final int NETWORK_TYPE_HSPAP = 15;

看到这个代码和注释,相信没有这方面知识的人很难看懂,都啥玩意?这注释跟没注释有啥区别?!就是让人看着更加闹心而已。所以说,注释对阅读代码的人很重 要。当然这些东西可能太专业了,写这些代码的人估计是想写也不知道该怎么了,得写多大一坨啊?!我在最后会贴上一些我整理的资料,可以供大家参考一下,不 是很详细,也不专业,就是大概有个印象。

TelephonyManager 还提供了 getNetworkTypeName(int type) 的方法,这个方法可以返回一个字符串,但是信息量不大。

那怎么判断是 2G , 3G 还是 4G 网络呢?TelephonyManager 还提供了另外一个方法,getNetworkClass(int networkType) ,但这个方法被隐藏掉了,我把代码贴一下。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static int getNetworkClass(int networkType) {
switch (networkType) {
case NETWORK_TYPE_GPRS:
case NETWORK_TYPE_EDGE:
case NETWORK_TYPE_CDMA:
case NETWORK_TYPE_1xRTT:
case NETWORK_TYPE_IDEN:
return NETWORK_CLASS_2_G;
case NETWORK_TYPE_UMTS:
case NETWORK_TYPE_EVDO_0:
case NETWORK_TYPE_EVDO_A:
case NETWORK_TYPE_HSDPA:
case NETWORK_TYPE_HSUPA:
case NETWORK_TYPE_HSPA:
case NETWORK_TYPE_EVDO_B:
case NETWORK_TYPE_EHRPD:
case NETWORK_TYPE_HSPAP:
return NETWORK_CLASS_3_G;
case NETWORK_TYPE_LTE:
return NETWORK_CLASS_4_G;
default:
return NETWORK_CLASS_UNKNOWN;
}
}

然后下面是这几个常量的值。

?
1
2
3
4
5
6
7
8
/** Unknown network class. {@hide} */
public static final int NETWORK_CLASS_UNKNOWN = 0;
/** Class of broadly defined "2G" networks. {@hide} */
public static final int NETWORK_CLASS_2_G = 1;
/** Class of broadly defined "3G" networks. {@hide} */
public static final int NETWORK_CLASS_3_G = 2;
/** Class of broadly defined "4G" networks. {@hide} */
public static final int NETWORK_CLASS_4_G = 3;

不知道为啥要把这些东西给隐藏起来,不靠谱?还是其他的更好的方式?!不知道,先这样吧,现在通过上面的手段,是可以知道用户用的是什么网络,当 然也可以区分出来用户使用的是 2G , 3G 还是 4G 了。当然,你获取到这些数据后,你也可以推算出用户用的是哪家公司的网络,移动的,联通的,还是电信的,当然,只在中国。而且虚拟运营商开始真正上市后, 这个就区分不出来是京东的,还是国美,苏宁的了,但是你可以知道你的手机号用的是联通的网还是移动的网。

最后贴上我收集整理的一些资料,可以参考一下。

  • GPRS       2G(2.5) General Packet Radia Service 114kbps
  • EDGE       2G(2.75G) Enhanced Data Rate for GSM Evolution 384kbps
  • UMTS      3G WCDMA 联通3G Universal Mobile Telecommunication System 完整的3G移动通信技术标准
  • CDMA     2G 电信 Code Division Multiple Access 码分多址
  • EVDO_0   3G (EVDO 全程 CDMA2000 1xEV-DO) Evolution - Data Only (Data Optimized) 153.6kps - 2.4mbps 属于3G
  • EVDO_A  3G 1.8mbps - 3.1mbps 属于3G过渡,3.5G
  • 1xRTT      2G CDMA2000 1xRTT (RTT - 无线电传输技术) 144kbps 2G的过渡,
  • HSDPA    3.5G 高速下行分组接入 3.5G WCDMA High Speed Downlink Packet Access 14.4mbps
  • HSUPA    3.5G High Speed Uplink Packet Access 高速上行链路分组接入 1.4 - 5.8 mbps
  • HSPA      3G (分HSDPA,HSUPA) High Speed Packet Access
  • IDEN      2G Integrated Dispatch Enhanced Networks 集成数字增强型网络 (属于2G,来自维基百科)
  • EVDO_B 3G EV-DO Rev.B 14.7Mbps 下行 3.5G
  • LTE        4G Long Term Evolution FDD-LTE 和 TDD-LTE , 3G过渡,升级版 LTE Advanced 才是4G
  • EHRPD  3G CDMA2000向LTE 4G的中间产物 Evolved High Rate Packet Data HRPD的升级
  • HSPAP  3G HSPAP 比 HSDPA 快些

实例:

?
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.List;
  
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
  
public class NetWorkUtil {
  
  public static boolean isWifiAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) ConfigManager
        .getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnected() && networkInfo
        .getType() == ConnectivityManager.TYPE_WIFI);
  }
  
  /**
   * 获取MAC地址
   *
   * @param context
   * @return
   */
  public static String getMacAddress(Context context) {
    if (context == null) {
      return "";
    }
  
    String localMac = null;
    if (isWifiAvailable()) {
      localMac = getWifiMacAddress(context);
    }
  
    if (localMac != null && localMac.length() > 0) {
      localMac = localMac.replace(":", "-").toLowerCase();
      return localMac;
    }
  
    localMac = getMacFromCallCmd();
    if (localMac != null) {
      localMac = localMac.replace(":", "-").toLowerCase();
    }
  
    return localMac;
  }
  
  private static String getWifiMacAddress(Context context) {
    String localMac = null;
    try {
      WifiManager wifi = (WifiManager) context
          .getSystemService(Context.WIFI_SERVICE);
      WifiInfo info = wifi.getConnectionInfo();
      if (wifi.isWifiEnabled()) {
        localMac = info.getMacAddress();
        if (localMac != null) {
          localMac = localMac.replace(":", "-").toLowerCase();
          return localMac;
        }
      }
  
    } catch (Exception e) {
      e.printStackTrace();
    }
  
    return null;
  }
  
  /**
   * 通过callCmd("busybox ifconfig","HWaddr")获取mac地址
   *
   * @attention 需要设备装有busybox工具
   * @return Mac Address
   */
  private static String getMacFromCallCmd() {
    String result = "";
    result = callCmd("busybox ifconfig", "HWaddr");
  
    if (result == null || result.length() <= 0) {
      return null;
    }
  
    DebugLog.v("tag", "cmd result : " + result);
  
    // 对该行数据进行解析
    // 例如:eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
    if (result.length() > 0 && result.contains("HWaddr") == true) {
      String Mac = result.substring(result.indexOf("HWaddr") + 6,
          result.length() - 1);
      if (Mac.length() > 1) {
        result = Mac.replaceAll(" ", "");
      }
    }
  
    return result;
  }
  
  public static String callCmd(String cmd, String filter) {
    String result = "";
    String line = "";
    try {
      Process proc = Runtime.getRuntime().exec(cmd);
      InputStreamReader is = new InputStreamReader(proc.getInputStream());
      BufferedReader br = new BufferedReader(is);
  
      // 执行命令cmd,只取结果中含有filter的这一行
      while ((line = br.readLine()) != null
          && line.contains(filter) == false) {
      }
  
      result = line;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
  
  /**
   * 网络是否可用
   *
   * @param context
   * @return
   */
  public static boolean IsNetWorkEnable(Context context) {
    try {
      ConnectivityManager connectivity = (ConnectivityManager) context
          .getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity == null) {
        ToastUtil.showMessage(context, "无法连接网络");
        return false;
      }
  
      NetworkInfo info = connectivity.getActiveNetworkInfo();
      if (info != null && info.isConnected()) {
        // 判断当前网络是否已经连接
        if (info.getState() == NetworkInfo.State.CONNECTED) {
          return true;
        }
      }
  
    } catch (Exception e) {
      e.printStackTrace();
    }
    ToastUtil.showMessage(context, "无法连接网络");
    return false;
  }
  
  private static final int NETWORK_TYPE_UNAVAILABLE = -1;
  // private static final int NETWORK_TYPE_MOBILE = -100;
  private static final int NETWORK_TYPE_WIFI = -101;
  
  private static final int NETWORK_CLASS_WIFI = -101;
  private static final int NETWORK_CLASS_UNAVAILABLE = -1;
  /** Unknown network class. */
  private static final int NETWORK_CLASS_UNKNOWN = 0;
  /** Class of broadly defined "2G" networks. */
  private static final int NETWORK_CLASS_2_G = 1;
  /** Class of broadly defined "3G" networks. */
  private static final int NETWORK_CLASS_3_G = 2;
  /** Class of broadly defined "4G" networks. */
  private static final int NETWORK_CLASS_4_G = 3;
  
  private static DecimalFormat df = new DecimalFormat("#.##");
  
  // 适配低版本手机
  /** Network type is unknown */
  public static final int NETWORK_TYPE_UNKNOWN = 0;
  /** Current network is GPRS */
  public static final int NETWORK_TYPE_GPRS = 1;
  /** Current network is EDGE */
  public static final int NETWORK_TYPE_EDGE = 2;
  /** Current network is UMTS */
  public static final int NETWORK_TYPE_UMTS = 3;
  /** Current network is CDMA: Either IS95A or IS95B */
  public static final int NETWORK_TYPE_CDMA = 4;
  /** Current network is EVDO revision 0 */
  public static final int NETWORK_TYPE_EVDO_0 = 5;
  /** Current network is EVDO revision A */
  public static final int NETWORK_TYPE_EVDO_A = 6;
  /** Current network is 1xRTT */
  public static final int NETWORK_TYPE_1xRTT = 7;
  /** Current network is HSDPA */
  public static final int NETWORK_TYPE_HSDPA = 8;
  /** Current network is HSUPA */
  public static final int NETWORK_TYPE_HSUPA = 9;
  /** Current network is HSPA */
  public static final int NETWORK_TYPE_HSPA = 10;
  /** Current network is iDen */
  public static final int NETWORK_TYPE_IDEN = 11;
  /** Current network is EVDO revision B */
  public static final int NETWORK_TYPE_EVDO_B = 12;
  /** Current network is LTE */
  public static final int NETWORK_TYPE_LTE = 13;
  /** Current network is eHRPD */
  public static final int NETWORK_TYPE_EHRPD = 14;
  /** Current network is HSPA+ */
  public static final int NETWORK_TYPE_HSPAP = 15;
  
  /**
   * 格式化大小
   *
   * @param size
   * @return
   */
  public static String formatSize(long size) {
    String unit = "B";
    float len = size;
    if (len > 900) {
      len /= 1024f;
      unit = "KB";
    }
    if (len > 900) {
      len /= 1024f;
      unit = "MB";
    }
    if (len > 900) {
      len /= 1024f;
      unit = "GB";
    }
    if (len > 900) {
      len /= 1024f;
      unit = "TB";
    }
    return df.format(len) + unit;
  }
  
  public static String formatSizeBySecond(long size) {
    String unit = "B";
    float len = size;
    if (len > 900) {
      len /= 1024f;
      unit = "KB";
    }
    if (len > 900) {
      len /= 1024f;
      unit = "MB";
    }
    if (len > 900) {
      len /= 1024f;
      unit = "GB";
    }
    if (len > 900) {
      len /= 1024f;
      unit = "TB";
    }
    return df.format(len) + unit + "/s";
  }
  
  public static String format(long size) {
    String unit = "B";
    float len = size;
    if (len > 1000) {
      len /= 1024f;
      unit = "KB";
      if (len > 1000) {
        len /= 1024f;
        unit = "MB";
        if (len > 1000) {
          len /= 1024f;
          unit = "GB";
        }
      }
    }
    return df.format(len) + "\n" + unit + "/s";
  }
  
  /**
   * 获取运营商
   *
   * @return
   */
  public static String getProvider() {
    String provider = "未知";
    try {
      TelephonyManager telephonyManager = (TelephonyManager) ConfigManager
          .getContext().getSystemService(Context.TELEPHONY_SERVICE);
      String IMSI = telephonyManager.getSubscriberId();
      Log.v("tag", "getProvider.IMSI:" + IMSI);
      if (IMSI == null) {
        if (TelephonyManager.SIM_STATE_READY == telephonyManager
            .getSimState()) {
          String operator = telephonyManager.getSimOperator();
          Log.v("tag", "getProvider.operator:" + operator);
          if (operator != null) {
            if (operator.equals("46000")
                || operator.equals("46002")
                || operator.equals("46007")) {
              provider = "中国移动";
            } else if (operator.equals("46001")) {
              provider = "中国联通";
            } else if (operator.equals("46003")) {
              provider = "中国电信";
            }
          }
        }
      } else {
        if (IMSI.startsWith("46000") || IMSI.startsWith("46002")
            || IMSI.startsWith("46007")) {
          provider = "中国移动";
        } else if (IMSI.startsWith("46001")) {
          provider = "中国联通";
        } else if (IMSI.startsWith("46003")) {
          provider = "中国电信";
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return provider;
  }
  
  /**
   * 获取网络类型
   *
   * @return
   */
  public static String getCurrentNetworkType() {
    int networkClass = getNetworkClass();
    String type = "未知";
    switch (networkClass) {
    case NETWORK_CLASS_UNAVAILABLE:
      type = "无";
      break;
    case NETWORK_CLASS_WIFI:
      type = "Wi-Fi";
      break;
    case NETWORK_CLASS_2_G:
      type = "2G";
      break;
    case NETWORK_CLASS_3_G:
      type = "3G";
      break;
    case NETWORK_CLASS_4_G:
      type = "4G";
      break;
    case NETWORK_CLASS_UNKNOWN:
      type = "未知";
      break;
    }
    return type;
  }
  
  private static int getNetworkClassByType(int networkType) {
    switch (networkType) {
    case NETWORK_TYPE_UNAVAILABLE:
      return NETWORK_CLASS_UNAVAILABLE;
    case NETWORK_TYPE_WIFI:
      return NETWORK_CLASS_WIFI;
    case NETWORK_TYPE_GPRS:
    case NETWORK_TYPE_EDGE:
    case NETWORK_TYPE_CDMA:
    case NETWORK_TYPE_1xRTT:
    case NETWORK_TYPE_IDEN:
      return NETWORK_CLASS_2_G;
    case NETWORK_TYPE_UMTS:
    case NETWORK_TYPE_EVDO_0:
    case NETWORK_TYPE_EVDO_A:
    case NETWORK_TYPE_HSDPA:
    case NETWORK_TYPE_HSUPA:
    case NETWORK_TYPE_HSPA:
    case NETWORK_TYPE_EVDO_B:
    case NETWORK_TYPE_EHRPD:
    case NETWORK_TYPE_HSPAP:
      return NETWORK_CLASS_3_G;
    case NETWORK_TYPE_LTE:
      return NETWORK_CLASS_4_G;
    default:
      return NETWORK_CLASS_UNKNOWN;
    }
  }
  
  private static int getNetworkClass() {
    int networkType = NETWORK_TYPE_UNKNOWN;
    try {
      final NetworkInfo network = ((ConnectivityManager) ConfigManager
          .getContext()
          .getSystemService(Context.CONNECTIVITY_SERVICE))
          .getActiveNetworkInfo();
      if (network != null && network.isAvailable()
          && network.isConnected()) {
        int type = network.getType();
        if (type == ConnectivityManager.TYPE_WIFI) {
          networkType = NETWORK_TYPE_WIFI;
        } else if (type == ConnectivityManager.TYPE_MOBILE) {
          TelephonyManager telephonyManager = (TelephonyManager) ConfigManager
              .getContext().getSystemService(
                  Context.TELEPHONY_SERVICE);
          networkType = telephonyManager.getNetworkType();
        }
      } else {
        networkType = NETWORK_TYPE_UNAVAILABLE;
      }
  
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return getNetworkClassByType(networkType);
  
  }
  
  public static String getWifiRssi() {
    int asu = 85;
    try {
      final NetworkInfo network = ((ConnectivityManager) ConfigManager
          .getContext()
          .getSystemService(Context.CONNECTIVITY_SERVICE))
          .getActiveNetworkInfo();
      if (network != null && network.isAvailable()
          && network.isConnected()) {
        int type = network.getType();
        if (type == ConnectivityManager.TYPE_WIFI) {
          WifiManager wifiManager = (WifiManager) ConfigManager
              .getContext()
              .getSystemService(Context.WIFI_SERVICE);
  
          WifiInfo wifiInfo = wifiManager.getConnectionInfo();
          if (wifiInfo != null) {
            asu = wifiInfo.getRssi();
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return asu + "dBm";
  }
  
  public static String getWifiSsid() {
    String ssid = "";
    try {
      final NetworkInfo network = ((ConnectivityManager) ConfigManager
          .getContext()
          .getSystemService(Context.CONNECTIVITY_SERVICE))
          .getActiveNetworkInfo();
      if (network != null && network.isAvailable()
          && network.isConnected()) {
        int type = network.getType();
        if (type == ConnectivityManager.TYPE_WIFI) {
          WifiManager wifiManager = (WifiManager) ConfigManager
              .getContext()
              .getSystemService(Context.WIFI_SERVICE);
  
          WifiInfo wifiInfo = wifiManager.getConnectionInfo();
          if (wifiInfo != null) {
            ssid = wifiInfo.getSSID();
            if (ssid == null) {
              ssid = "";
            }
            ssid = ssid.replaceAll("\"", "");
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return ssid;
  }
  
  /**
   * 检查sim卡状态
   *
   * @param ctx
   * @return
   */
  public static boolean checkSimState() {
    TelephonyManager tm = (TelephonyManager) ConfigManager.getContext()
        .getSystemService(Context.TELEPHONY_SERVICE);
    if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
        || tm.getSimState() == TelephonyManager.SIM_STATE_UNKNOWN) {
      return false;
    }
  
    return true;
  }
  
  /**
   * 获取imei
   */
  public static String getImei() {
    TelephonyManager mTelephonyMgr = (TelephonyManager) ConfigManager
        .getContext().getSystemService(Context.TELEPHONY_SERVICE);
    String imei = mTelephonyMgr.getDeviceId();
    if (imei == null) {
      imei = "000000000000000";
    }
    return imei;
  }
  
  public static String getPhoneImsi() {
    TelephonyManager mTelephonyMgr = (TelephonyManager) ConfigManager
        .getContext().getSystemService(Context.TELEPHONY_SERVICE);
    return mTelephonyMgr.getSubscriberId();
  }
  
  public static CellInfo getNetInfo() {
    CellInfo info = new CellInfo();
    try {
      TelephonyManager mTelephonyManager = (TelephonyManager) ConfigManager
          .getContext().getSystemService(Context.TELEPHONY_SERVICE);
      String operator = mTelephonyManager.getNetworkOperator();
      if (operator != null) {
        /** 通过operator获取 MCC 和MNC */
        if (operator.length() > 3) {
          String mcc = operator.substring(0, 3);
          String mnc = operator.substring(3);
          info.setMcc(mcc);
          info.setMnc(mnc);
        }
      }
  
      int lac = 0;
      int cellId = 0;
      int phoneType = mTelephonyManager.getPhoneType();
      if (phoneType == TelephonyManager.PHONE_TYPE_GSM) {
        GsmCellLocation location = (GsmCellLocation) mTelephonyManager
            .getCellLocation();
        /** 通过GsmCellLocation获取中国移动和联通 LAC 和cellID */
        lac = location.getLac();
        cellId = location.getCid();
      } else if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
        CdmaCellLocation location = (CdmaCellLocation) mTelephonyManager
            .getCellLocation();
        lac = location.getNetworkId();
        cellId = location.getBaseStationId();
        cellId /= 16;
      }
      if (lac == 0 || cellId == 0) {
        List<NeighboringCellInfo> infos = mTelephonyManager
            .getNeighboringCellInfo();
        int lc = 0;
        int ci = 0;
        int rssi = 0;
        for (NeighboringCellInfo cell : infos) {
          // 根据邻区总数进行循环
          if (lc == 0 || ci == 0) {
            lc = cell.getLac();
            ci = cell.getCid();
            rssi = cell.getRssi();
          }
          // sb.append(" LAC : " + info.getLac());
          // // 取出当前邻区的LAC
          // sb.append(" CID : " + info.getCid());
          // // 取出当前邻区的CID
          // sb.append(" BSSS : " + (-113 + 2 * info.getRssi()) +
          // "\n"); // 获取邻区基站信号强度
        }
        rssi = -113 + 2 * rssi;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return info;
  }
  
}

希望本文所述对大家学习Android软件编程有所帮助。

延伸 · 阅读

精彩推荐