如何在Flutter中获取手机SIM卡的ICCID号?求可用插件推荐
在Flutter中获取SIM卡ICCID的方法及可用插件
可用插件推荐
目前有两个Flutter插件支持获取SIM卡ICCID,无需自行编写大量原生代码:
1. telephony 插件
这是一个功能全面的通讯类插件,支持获取SIM卡信息(包括ICCID)、短信、通话记录等。
添加依赖:
在pubspec.yaml中加入:dependencies: telephony: ^0.2.0执行
flutter pub get完成安装。配置权限:
- Android:在
android/app/src/main/AndroidManifest.xml中添加权限:<uses-permission android:name="android.permission.READ_PHONE_STATE"/> - iOS:在
ios/Runner/Info.plist中添加权限说明:<key>NSPhoneUsageDescription</key> <string>需要访问SIM卡信息以获取ICCID</string>
- Android:在
代码实现:
import 'package:telephony/telephony.dart'; final Telephony telephony = Telephony.instance; void getICCID() async { // 先请求权限 bool hasPermission = await telephony.requestPhonePermissions(); if (hasPermission) { SimData simData = await telephony.getSimData(); String iccid = simData.iccid; print("ICCID: $iccid"); } else { print("权限未授予,无法获取ICCID"); } }
2. sim_card_info 插件
专注于SIM卡信息获取的轻量插件,API更简洁。
添加依赖:
在pubspec.yaml中加入:dependencies: sim_card_info: ^1.0.0执行
flutter pub get完成安装。权限配置:
权限要求和telephony插件一致,需配置Android的READ_PHONE_STATE权限和iOS的权限说明。代码实现:
import 'package:sim_card_info/sim_card_info.dart'; void fetchICCID() async { try { String? iccid = await SimCardInfo.getIccid; if (iccid != null) { print("ICCID: $iccid"); } else { print("无法获取ICCID"); } } catch (e) { print("获取ICCID出错: $e"); } }
自定义原生桥接方案(如果插件不满足需求)
如果现有插件无法适配你的场景,可以自行编写Flutter与原生的桥接代码:
Android端(Kotlin)
import android.content.Context import android.telephony.TelephonyManager import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel class SimCardICCIDPlugin : FlutterPlugin, MethodChannel.MethodCallHandler { private lateinit var channel: MethodChannel private lateinit var context: Context override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { context = binding.applicationContext channel = MethodChannel(binding.binaryMessenger, "sim_card_iccid_channel") channel.setMethodCallHandler(this) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { if (call.method == "getICCID") { val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager // 注意:Android 10+ 需要READ_PRIVILEGED_PHONE_STATE权限,普通应用无法获取 val iccid = telephonyManager.simSerialNumber result.success(iccid) } else { result.notImplemented() } } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) } }
Flutter端调用
import 'package:flutter/services.dart'; class ICCIDService { static const MethodChannel _channel = MethodChannel('sim_card_iccid_channel'); static Future<String?> getICCID() async { try { return await _channel.invokeMethod('getICCID'); } on PlatformException catch (e) { print("获取ICCID失败: ${e.message}"); return null; } } }
注意事项
- 必须申请对应权限,否则无法获取ICCID
- Android 10及以上版本,普通应用无法获取ICCID(需要系统级权限),这是系统限制
- 部分双卡设备或虚拟设备可能返回null或空值
- iOS上需要用户明确授权后才能获取
内容的提问来源于stack exchange,提问作者Kirthana
相关产品推荐
相关产品推荐

