Flutter如何通过cell_info插件每隔X秒更新手机状态数据到文本
实现周期性拉取手机基站信号数据的方案
原有代码说明
你当前使用的cell_info Flutter插件可获取基站信号强度、主小区/邻区列表等数据,原有逻辑仅在页面初始化时拉取一次数据。
改造步骤
- 新增定时器实例变量,页面销毁时需要主动销毁定时器避免内存泄漏
- 初始化完成首次数据拉取后,启动周期性定时器,定时触发数据拉取逻辑
- 无需修改原有数据解析、界面更新逻辑
完整改造后代码
import 'dart:async'; import 'dart:convert'; import 'package:cell_info/CellResponse.dart'; import 'package:cell_info/cell_info.dart'; import 'package:cell_info/models/common/cell_type.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { CellsResponse? _cellsResponse; // 新增定时器变量 Timer? _cellInfoTimer; // 自定义拉取间隔,单位秒,可按需修改 final int _pullInterval = 5; @override void initState() { super.initState(); // 首次拉取数据 initPlatformState(); // 启动周期性定时器 _startTimer(); } @override void dispose() { // 页面销毁时取消定时器 _cellInfoTimer?.cancel(); super.dispose(); } String currentDBM = ""; // 启动定时器方法 void _startTimer() { _cellInfoTimer = Timer.periodic(Duration(seconds: _pullInterval), (timer) { // 定时触发数据拉取 initPlatformState(); }); } // 原有数据拉取解析逻辑无需修改 Future<void> initPlatformState() async { CellsResponse? cellsResponse; try { String platformVersion = await CellInfo.getCellInfo; final body = json.decode(platformVersion); cellsResponse = CellsResponse.fromJson(body); CellType currentCellInFirstChip = cellsResponse.primaryCellList[0]; if (currentCellInFirstChip.type == "LTE") { currentDBM = "LTE dbm = " + currentCellInFirstChip.lte.signalLTE.dbm.toString(); } else if (currentCellInFirstChip.type == "NR") { currentDBM = "NR dbm = " + currentCellInFirstChip.nr.signalNR.dbm.toString(); } else if (currentCellInFirstChip.type == "WCDMA") { currentDBM = "WCDMA dbm = " + currentCellInFirstChip.wcdma.signalWCDMA.dbm.toString(); } } on PlatformException { cellsResponse = null; } if (!mounted) return; setState(() { _cellsResponse = cellsResponse; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('基站信号监测'), ), body: _cellsResponse != null ? Center( child: Text( '当前信号强度:${currentDBM}\n主小区数量:${_cellsResponse!.primaryCellList.length} \n邻区数量:${_cellsResponse!.neighboringCellList.length}'), ) : const Center(child: CircularProgressIndicator()), ), ); } }
注意事项
- 拉取间隔不要设置过短,建议最短不低于2秒,避免频繁调用原生接口导致系统资源占用过高
- 可根据需求新增权限申请逻辑,Android 12及以上版本需要获取精确定位权限才能正常读取基站信息
- 信号读取失败时可新增重试逻辑,避免单次读取异常导致页面无数据
内容的提问来源于stack exchange,提问作者Mahmoud Al-Haroon
相关产品推荐
相关产品推荐

