network_connectivity.dart 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import 'dart:async';
  2. import 'dart:math';
  3. import 'package:connectivity_plus/connectivity_plus.dart';
  4. import 'package:vnote_device_plugin/events/event_type.dart';
  5. import 'package:vitalapp/architecture/utils/prompt_box.dart';
  6. import 'package:fis_common/logger/logger.dart';
  7. /// 网络连接检测器 - 全局实例
  8. final netChecker = _init();
  9. NetworkConnectivityChecker _init() {
  10. final instance = NetworkConnectivityChecker._();
  11. bool isConnecting = true;
  12. instance.onlineChangedEvent.addListener((sender, e) {
  13. if (e) {
  14. if (!isConnecting) {
  15. // TODO: 暂时不提示
  16. // PromptBox.toast("网络已连接");
  17. }
  18. } else {
  19. // TODO: 暂时不提示
  20. // PromptBox.error("网络已断开");
  21. }
  22. isConnecting = e;
  23. });
  24. return instance;
  25. }
  26. /// 网络连接检查器
  27. class NetworkConnectivityChecker {
  28. NetworkConnectivityChecker._();
  29. final Connectivity _api = Connectivity();
  30. StreamSubscription<ConnectivityResult>? _subscription;
  31. ConnectivityResult _status = ConnectivityResult.none;
  32. /// 在线状态变更事件
  33. final FEventHandler<bool> onlineChangedEvent = FEventHandler<bool>();
  34. /// 连接状态
  35. ConnectivityResult get status => _status;
  36. /// 是否在线
  37. bool get isOnline => status != ConnectivityResult.none;
  38. void run() {
  39. if (_subscription != null) {
  40. return;
  41. }
  42. _subscription = _api.onConnectivityChanged.listen((event) {
  43. logger.i(
  44. "NetworkConnectivityChecker - Current net connection type: ${event.name}.");
  45. _update(event);
  46. logger.i("NetworkConnectivityChecker - IsOnline: $isOnline.");
  47. });
  48. }
  49. void stop() {
  50. _subscription?.cancel();
  51. _subscription = null;
  52. }
  53. /// 手动检查
  54. Future<bool> check() async {
  55. logger.i("NetworkConnectivityChecker - Check start.");
  56. final result = await _api.checkConnectivity();
  57. logger.i("NetworkConnectivityChecker - Check result:${result.name}.");
  58. _update(result);
  59. logger.i("NetworkConnectivityChecker - IsOnline: $isOnline.");
  60. return isOnline;
  61. }
  62. void _update(ConnectivityResult result) {
  63. _status = result;
  64. onlineChangedEvent.emit(this, isOnline);
  65. }
  66. }