admin
2022-05-12 fa705507ba574c857b1667553737d23b1b7ff495
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
import 'package:flutter/services.dart';
 
typedef OnNetWorkChanged = void Function(ConnectivityResult);
 
List<OnNetWorkChanged> _notifyList = [];
 
ConnectivityResult _getNetwork(String network) {
  if (network == "1") {
    return ConnectivityResult.mobile;
  } else if (network == "2") {
    return ConnectivityResult.wifi;
  } else {
    return ConnectivityResult.none;
  }
}
 
class Connectivity {
  static Connectivity? _singleton;
 
  static final NetWorkMethodChannel _netWorkMethodChannel =
      NetWorkMethodChannel("com.yeshi.video/network");
 
  Connectivity._();
 
  factory Connectivity() {
    _singleton ??= Connectivity._();
    return _singleton!;
  }
 
  Future<ConnectivityResult> checkConnectivity() async {
    String network =
        await _netWorkMethodChannel.invokeMethod("getCurrentNetwork");
    print("当前网络状态$network");
    return _getNetwork(network);
  }
 
  OnNetWorkChanged listen(OnNetWorkChanged changed) {
    _notifyList.add(changed);
    return changed;
  }
 
  remove(OnNetWorkChanged changed) {
    _notifyList.remove(changed);
  }
}
 
class NetWorkMethodChannel extends MethodChannel {
  NetWorkMethodChannel(String name) : super(name) {
    setMethodCallHandler((call) {
      switch (call.method) {
        case "onNetworkChanged":
          {
            print("网络连接状态改变${call.arguments}");
            String network = call.arguments;
            _notifyList.forEach((element) {
              element(_getNetwork(network));
            });
          }
      }
      return Future.value();
    });
  }
}
 
enum ConnectivityResult {
  /// WiFi: Device connected via Wi-Fi
  wifi,
 
  /// Mobile: Device connected to cellular network
  mobile,
 
  /// None: Device not connected to any network
  none
}