Flutter网络功能增强插件bheya_network的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter网络功能增强插件bheya_network的使用

BHEYA_NETWORK
这个插件是对 nr_cellinfo 的改进。

Cell Info 插件

这是一个基于 Telephony SDK 构建的轻量级 Android 库。NetMonster 核心是从 NetMonster 应用程序中提取的,并为较旧的 Android 设备回退了多个电信功能。

为什么使用 NetMonster Core 而不是遗留 API?

  • 验证:库验证来自 RIL 的数据并尽可能进行修正
  • 丰富的信息:提供了更多有关小区标识和信号的功能,使您的代码更易理解
  • 回退支持:一些不可访问的信号或标识字段现在可以通过简单的代码访问
  • 经过测试:在真实设备上进行了测试,拥有超过 50,000 名活跃用户

新功能

以下是每个语音/数据网络的小型比较。

GSM

功能 最小 Android SDK 版本 最小 NetMonster Core SDK 版本
CGI - I (14)
NCC - N (24)
BCC - N (24)
Band - N (24)
TA O (26) N (24)

WCDMA

功能 最小 Android SDK 版本 最小 NetMonster Core SDK 版本
CGI - I (14)
CID (16b) - I (14)
RNC - I (14)
Ec/Io - M (23)
Band - N (24)
BER - Q (29)
Ec/No - Q (29)
RSCP - Q (29)

LTE

功能 最小 Android SDK 版本 最小 NetMonster Core SDK 版本
eCGI - I (14)
CID (8b) - I (14)
eNb - I (14)
RSSI Q (29) I (14)
RSRP O (26) I (14)
CQI O (26) I (14)
SNR O (26) I (14)
TA O (26) I (14)
Band - N (24)

使用

基本上有两种方式可以使用这个库:

  1. 作为验证库:该库将清理来自 AOSP 的数据,因为许多制造商修改了源代码且未遵循公共文档。在这种情况下,您只需要使用 ITelephonyManagerCompat 来获取符合 AOSP 模式的正确验证数据。

  2. 利用额外后处理的优势:这样可以获得更多的数据,但准确性可能不完全保证。

不带额外后处理

NetMonster Core 专注于映射 AOSP 提供的两种获取当前小区信息的方法:

注意:其中一些方法已被废弃或从 AOSP 中移除,更多信息请参见每个方法的文档。

后处理

在这种情况下,您需要与 INetMonster 类交互。以下是此库解决的一些问题列表。

合并来自多个来源的数据

问题:

  • Android 提供了多种获取小区信息的方式。
  • 并非所有设备都支持一种统一的方式来访问所有数据。

解决方案:

  • NetMonster Core 从您指定的来源抓取数据,验证并合并它们。
检测 LTE-A 和 HSPA+42

问题:

  • AOSP 无法检测 HSPA+42,只能检测 HSPA+。
  • AOSP 没有提供区分当前网络是否使用载波聚合的方法。

解决方案:

  • NetMonster Core 尝试猜测 HSPA+ 42 的可用性。
  • 基于小区信息可以猜测 LTE-CA 的存在,或者使用隐藏的 API 进行检测。

使用 getNetworkType(vararg detectors: INetworkDetector) 可以指定使用哪种 INetworkDetector 来检测当前网络类型。

其他功能
  • 检测“仅限紧急呼叫”模式下的服务小区。
  • 在 GSM、WCDMA、LTE、TD-SCDMA 和 NR 网络中为非服务小区添加 PLMN。

许可证

Copyright 2019 Eslam Faisal

Licensed under the Apache License, Version 2.0 (the "License");

you may not use this file except in compliance with the License.
You may obtain a copy of the License at


http://www.apache.org/licenses/LICENSE-2.0


Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and

预览

| Screen1| Screen13 | |---------|

| Screen2| Screen12 | |---------|

| Screen3| Screen11 | |---------|

| Screen4| Screen10 | |---------|

| Screen5| Screen8 | |---------|

示例代码

以下是一个完整的示例代码,展示如何使用 bheya_network 插件来获取网络信息。

import 'dart:convert';

import 'package:bheya_network/cellResponse.dart';
import 'package:bheya_network/models/common/cell_type.dart';
import 'package:flutter/material.dart';
import 'package:bheya_network/bheya_network.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  CellsResponse? _cellsResponse;

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  String currentDBM = "";

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    await providerCheckPermission();
    CellsResponse? cellsResponse;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      String platformVersion = (await BheyaNetwork.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}";
      } else if (currentCellInFirstChip.type == "NR") {
        currentDBM = "NR dbm = ${currentCellInFirstChip.nr!.signalNR!.dbm}";
      } else if (currentCellInFirstChip.type == "WCDMA") {
        currentDBM =
            "WCDMA dbm = ${currentCellInFirstChip.wcdma!.signalWCDMA!.dbm}";
      }
      // String simInfo = (await BheyaNetwork.getSIMInfo) ?? "";
      // final simJson = json.decode(simInfo);
    } on PlatformException {
      _cellsResponse = null;
    }

    if (!mounted) return;

    setState(() {
      _cellsResponse = cellsResponse;
    });
  }

  providerCheckPermission() async {
    await [
      Permission.location,
      Permission.storage,
      Permission.phone,
      Permission.locationWhenInUse,
    ].request();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: _cellsResponse != null
            ? Center(
                child: Text(
                    'david = $currentDBM\n primary = ${_cellsResponse!.primaryCellList!.length.toString()} \n neighbor = ${_cellsResponse!.neighboringCellList!.length}'),
              )
            : null,
      ),
    );
  }
}

更多关于Flutter网络功能增强插件bheya_network的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网络功能增强插件bheya_network的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


bheya_network 是一个用于增强 Flutter 应用网络功能的插件。它提供了一些有用的功能,如网络状态监听、网络请求重试、缓存管理等。以下是如何在 Flutter 项目中使用 bheya_network 的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 bheya_network 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  bheya_network: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化插件

在你的应用中初始化 bheya_network 插件。通常,你可以在 main.dart 文件的 main 函数中进行初始化:

import 'package:bheya_network/bheya_network.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 bheya_network
  await BheyaNetwork.initialize();

  runApp(MyApp());
}

3. 监听网络状态

bheya_network 提供了网络状态监听功能。你可以使用 BheyaNetwork 类来监听网络状态的变化:

import 'package:bheya_network/bheya_network.dart';

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Bheya Network Example'),
        ),
        body: Center(
          child: BheyaNetworkListener(
            builder: (context, networkStatus) {
              return Text('Network Status: ${networkStatus.toString()}');
            },
          ),
        ),
      ),
    );
  }
}

4. 网络请求重试

bheya_network 还提供了网络请求重试功能。你可以使用 BheyaNetworkRetry 类来处理网络请求失败时的重试逻辑:

import 'package:bheya_network/bheya_network.dart';

class MyApp extends StatelessWidget {
  Future<void> fetchData() async {
    final response = await BheyaNetworkRetry.retry(
      () => http.get(Uri.parse('https://example.com/data')),
      maxRetryAttempts: 3,
    );

    if (response.statusCode == 200) {
      print('Data fetched successfully');
    } else {
      print('Failed to fetch data');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Bheya Network Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: fetchData,
            child: Text('Fetch Data'),
          ),
        ),
      ),
    );
  }
}

5. 缓存管理

bheya_network 还支持缓存管理功能。你可以使用 BheyaNetworkCache 类来缓存网络请求的响应数据:

import 'package:bheya_network/bheya_network.dart';

class MyApp extends StatelessWidget {
  Future<void> fetchData() async {
    final cachedResponse = await BheyaNetworkCache.get('https://example.com/data');

    if (cachedResponse != null) {
      print('Data fetched from cache');
    } else {
      final response = await http.get(Uri.parse('https://example.com/data'));
      await BheyaNetworkCache.set('https://example.com/data', response);
      print('Data fetched from network and cached');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Bheya Network Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: fetchData,
            child: Text('Fetch Data'),
          ),
        ),
      ),
    );
  }
}

6. 其他功能

bheya_network 还提供了其他一些功能,如请求超时设置、自定义请求头等。你可以查阅官方文档或源码来了解更多详细信息。

7. 清理资源

在应用退出时,你可能需要清理 bheya_network 占用的资源。你可以在 dispose 方法中进行清理:

[@override](/user/override)
void dispose() {
  BheyaNetwork.dispose();
  super.dispose();
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!