Flutter电话功能插件flutter_phone的使用
Flutter电话功能插件flutter_phone的使用
Flutter插件flutter_phone
用于实现电话拨号、通话记录、音频等功能。
使用步骤
1. 添加依赖
在pubspec.yaml
文件中添加以下依赖:
dependencies:
flutter_phone: ^版本号
然后执行flutter pub get
以安装依赖。
2. 初始化插件
创建一个FlutterPhone
实例,并在initState
方法中初始化平台状态。
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_phone/flutter_phone.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
final _phone = FlutterPhone();
[@override](/user/override)
void initState() {
super.initState();
initPlatformState();
}
3. 获取平台版本
通过调用getPlatformVersion
方法获取平台版本信息。
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await _phone.getPlatformVersion() ?? 'Unknown platform version';
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
4. 请求权限
请求电话权限,确保应用可以拨打电话。
await _phone.permission();
5. 拨打电话
使用toCall
方法拨打电话,传入电话号码和ID。
// _phone.toCall({"phone":"13578021300","id":0});
6. 同步通话录音
通过传递参数调用appTask
方法同步通话录音。
Map map = {
// 通用设置
"_t": _t,
"domain": url, // 替换为实际接口地址
"endpoint": "https://oss-cn-beijing.aliyuncs.com", // oss区域对应域名(固定)
"bucketName": "kingchem", // bucketName(固定)
"identification": identification, // 替换为设备id
"stsServer": "/api/audio/securityToken", // 获取oss鉴权信息(域名+接口地址+当前登录token)
// 通话录音
"time": 86400 * day * 1000, // 通话录音-时间范围
"dir": 'dtms/$env/audio/$identification/', // 通话录音-录音文件上传目录
"uploadAlways": 0, // 通话录音-(未实现)缓存是否已上传录音文件:0是,1否
"logsCat": "[call,audio,match]", // 日志显示分类
"callCnfServer": "/api/audio/callCnf", // 通话录音-用户配置信息(未实现)
"callSaveServer": "/mobile/call/saveLog", // 通话录音-通话记录上传
"audioStatusServer": "/mobile/call/noticeUpload", // 通话录音-更新录音状态接口
"audioFileUploadServer": "/mobile/call/audioFileUpload", // 通话录音-原始录音文件信息保存
};
_phone.appTask(map);
7. 构建UI
构建一个简单的UI,显示平台版本并提供按钮触发同步操作。
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text('Running on: $_platformVersion\n', textAlign: TextAlign.center,),
TextButton(
onPressed: initPlatformState,
child: Text("同步通话录音"),
style: ButtonStyle(
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 18)),
padding: MaterialStateProperty.all(EdgeInsets.all(10)),
backgroundColor: MaterialStateProperty.all(Colors.red),
foregroundColor: MaterialStateProperty.all(Colors.amberAccent)
),
)
],
),
)
),
);
}
}
完整示例代码
以下是完整的示例代码:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_phone/flutter_phone.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
final _phone = FlutterPhone();
[@override](/user/override)
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await _phone.getPlatformVersion() ?? 'Unknown platform version';
await _phone.permission();
// 获取通话记录和录音&&上传
String url = "http://192.168.110.14:9514"; // 替换为实际接口地址
String _t = "41e4cdf892bfee3080618621643a6086"; // 替换为实际token
String identification = "4d507500cc7a5398"; // 替换为实际设备id
String env = "prod"; // 替换为实际环境
int day = 50; // 替换为实际天数
Map map = {
// 通用设置
"_t": _t,
"domain": url,
"endpoint": "https://oss-cn-beijing.aliyuncs.com",
"bucketName": "kingchem",
"identification": identification,
"stsServer": "/api/audio/securityToken",
// 通话录音
"time": 86400 * day * 1000,
"dir": 'dtms/$env/audio/$identification/',
"uploadAlways": 0,
"logsCat": "[call,audio,match]",
"callCnfServer": "/api/audio/callCnf",
"callSaveServer": "/mobile/call/saveLog",
"audioStatusServer": "/mobile/call/noticeUpload",
"audioFileUploadServer": "/mobile/call/audioFileUpload",
};
_phone.appTask(map);
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text('Running on: $_platformVersion\n', textAlign: TextAlign.center,),
TextButton(
onPressed: initPlatformState,
child: Text("同步通话录音"),
style: ButtonStyle(
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 18)),
padding: MaterialStateProperty.all(EdgeInsets.all(10)),
backgroundColor: MaterialStateProperty.all(Colors.red),
foregroundColor: MaterialStateProperty.all(Colors.amberAccent)
),
)
],
),
)
),
);
}
}
更多关于Flutter电话功能插件flutter_phone的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter电话功能插件flutter_phone的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
flutter_phone
是一个用于在 Flutter 应用中实现电话功能的插件。它允许你拨打电话号码、监听电话状态等。以下是如何使用 flutter_phone
插件的详细步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 flutter_phone
插件的依赖:
dependencies:
flutter:
sdk: flutter
flutter_phone: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来获取依赖。
2. 配置权限
为了拨打电话,你需要在 AndroidManifest.xml
文件中添加以下权限:
<uses-permission android:name="android.permission.CALL_PHONE" />
对于 iOS,你需要在 Info.plist
文件中添加以下权限:
<key>NSPhoneNumberUsageDescription</key>
<string>我们需要访问您的电话功能以拨打电话</string>
3. 使用插件
在你的 Dart 代码中,你可以使用 flutter_phone
插件来拨打电话。以下是一个简单的示例:
import 'package:flutter/material.dart';
import 'package:flutter_phone/flutter_phone.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Phone Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
// 拨打电话
await FlutterPhone.makePhoneCall('1234567890');
},
child: Text('Call 1234567890'),
),
),
),
);
}
}
4. 处理权限请求
在 Android 6.0(API 23)及以上版本中,你需要在运行时请求 CALL_PHONE
权限。你可以使用 permission_handler
插件来处理权限请求。
首先,添加 permission_handler
依赖:
dependencies:
permission_handler: ^10.0.0 # 请使用最新版本
然后,在拨打电话之前请求权限:
import 'package:permission_handler/permission_handler.dart';
void makePhoneCall() async {
// 请求电话权限
var status = await Permission.phone.request();
if (status.isGranted) {
// 权限已授予,拨打电话
await FlutterPhone.makePhoneCall('1234567890');
} else {
// 权限被拒绝,显示提示
print('Permission denied');
}
}
5. 监听电话状态
flutter_phone
插件还允许你监听电话状态。你可以使用 FlutterPhone.onPhoneStateChanged
来监听电话状态的变化:
FlutterPhone.onPhoneStateChanged.listen((state) {
print('Phone state changed: $state');
});
6. 处理错误
在拨打电话时,可能会遇到各种错误,例如权限被拒绝、电话号码无效等。你可以使用 try-catch
块来处理这些错误:
try {
await FlutterPhone.makePhoneCall('1234567890');
} catch (e) {
print('Failed to make phone call: $e');
}