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
|
}
|