Flutter集成Everlink服务插件everlink_sdk的使用
Flutter集成Everlink服务插件everlink_sdk的使用
允许使用Flutter开发的应用程序通过超声波实现邻近验证。
安装
Android
- 编辑
android/build.gradle
文件,使其看起来像这样:
allprojects {
repositories {
...
google()
mavenCentral()
maven {
url "https://repo.everlink.co/repository/maven-releases/"
}
}
}
如果需要,同步项目。
iOS
- 在终端中,导航到项目的
ios/
目录。 - 使用CocoaPods安装项目依赖项:
$ cd your_flutter_project/ios/
$ pod install
- 在Xcode中,编辑位于Runner > Runner的
Info.plist
文件。添加麦克风使用描述以获取麦克风访问权限。
使用
- 导入
everlink_sdk.dart
和everlink_sdk_event.dart
:
import 'package:everlink_sdk/everlink_sdk.dart';
import 'package:everlink_sdk/everlink_sdk_event.dart';
- 初始化
EverlinkSdk
类并传递您的应用ID密钥:
final everlinkSdk = EverlinkSdk("your appID key");
- 设置事件监听器:
[@override](/user/override)
void initState() {
super.initState();
_listenToSdkEvents();
}
void _listenToSdkEvents() {
everlinkSdk.onEvent.listen((event) {
if (event is GeneratedTokenEvent) {
log('Generated token: Old - ${event.oldToken}, New - ${event.newToken}');
// 新生成的令牌,保存到数据库
} else if (event is DetectionEvent) {
doSomethingWithDetectedToken(event.detectedToken);
// 可以通过返回的令牌识别听到的位置/设备
}
}, onError: (error) {
log('Error receiving SDK event: $error');
});
}
- 检测代码:
Future<void> everlinkStartDetecting() async {
await everlinkSdk.startDetecting();
}
Future<void> everlinkStopDetecting() async {
await everlinkSdk.stopDetecting();
}
注意用户将被提示授予麦克风权限。成功检测后,我们将通过 everlink_sdk_event
EventChannel 广播流返回检测到设备的标识令牌。您需要再次调用 startDetecting()
来检测另一个音频码。
您可以现在搜索您的数据库或本地使用返回的 Everlink 唯一标识符来查找已检测到的用户。例如:
"SELECT * FROM employees WHERE everlink_token = token";
- 发送代码:
Future<void> everlinkStartEmitting() async {
await everlinkSdk.startEmitting();
}
Future<void> everlinkStopEmitting() async {
await everlinkSdk.stopEmitting();
}
这将导致设备开始发出最新生成的令牌的音频码。您还可以作为参数传递一个令牌,其音频码将播放,如下所示:
Future<void> everlinkStartEmittingToken(String token) async {
await everlinkSdk.startEmittingToken(token);
}
- 音量设置:
允许您设置音量以及是否应默认为扬声器播放音频:
Future<void> everlinkPlayVolume(double volume, bool loudSpeaker) async {
await everlinkSdk.playVolume(volume, loudSpeaker);
}
我们可以检测耳机是否在使用,并将音频路由到设备的扬声器。尽管用户可能会在他们正在听的任何音频中短暂暂停,但在中断之前我们会自动恢复播放。
- 创建令牌:
如果您希望手动生成一个新的用户令牌。否则将自动生成。
Future<void> everlinkNewToken(String date, [int? validityPeriod]) async {
await everlinkSdk.newToken(date, validityPeriod);
}
成功检测后,我们将通过 everlink_sdk_event
EventChannel 广播流返回听到设备的标识令牌。
- 下载令牌(如需离线工作)
Future<void> everlinkSaveTokens(List<String> tokens) async {
await everlinkSdk.saveTokens(tokens);
}
对于可以提前下载用户令牌的情况,我们强烈建议您这样做。这将减少延迟并使验证更快更可靠。
错误处理
Everlink SDK 提供了强大的错误处理功能,使用 EverlinkError
类封装错误代码和消息,以便于调试和一致性。平台调用的错误会使用 toEverlinkError
扩展转换为 EverlinkError
。
示例:处理启动检测时的错误
设置Everlink
void setupEverlink() async {
try {
await everlinkSdk.setupEverlink('yourAppID');
print('Setup completed successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
启动检测
void startDetection() async {
try {
await everlinkSdk.startDetecting();
print('Detection started successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
停止检测
void stopDetection() async {
try {
await everlinkSdk.stopDetecting();
print('Detection stopped successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
生成新令牌
void generateNewToken(String date) async {
try {
await everlinkSdk.newToken(date);
print('New token generated successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
保存令牌
void saveTokens(List<String> tokens) async {
try {
await everlinkSdk.saveTokens(tokens);
print('Tokens saved successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
清除令牌
void clearTokens() async {
try {
await everlinkSdk.clearTokens();
print('Tokens cleared successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
开始发射
void startEmitting() async {
try {
await everlinkSdk.startEmitting();
print('Started emitting successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
开始发射令牌
void startEmittingToken(String token) async {
try {
await everlinkSdk.startEmittingToken(token);
print('Started emitting token successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
停止发射
void stopEmitting() async {
try {
await everlinkSdk.stopEmitting();
print('Stopped emitting successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
更改播放音量
void changeVolume(double volume, bool loudSpeaker) async {
try {
await everlinkSdk.playVolume(volume, loudSpeaker);
print('Volume changed successfully.');
} on EverlinkError catch (e) {
print('Error occurred: ${e.toString()}');
} catch (e) {
print('Unexpected error: $e');
}
}
示例代码
以下是使用Everlink SDK的完整示例Demo:
import 'dart:async';
import 'dart:developer';
import 'package:everlink_sdk/everlink_sdk.dart';
import 'package:everlink_sdk/everlink_sdk_event.dart';
import 'package:everlink_sdk/everlink_error.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _everlinkSdk = EverlinkSdk("com.everlink.everlink_sdk_example");
// 颜色
Color _currentBackgroundColor = const Color.fromRGBO(38, 40, 74, 1.0);
// 恒定颜色用于背景
final _buttonColor = const Color.fromRGBO(255, 107, 107, 1.0);
final _doSomethingBackgroundColor = const Color.fromRGBO(7, 250, 52, 1.0);
final _defaultBackgroundColor = const Color.fromRGBO(38, 40, 74, 1.0);
[@override](/user/override)
void initState() {
super.initState();
_listenToSdkEvents();
}
void _listenToSdkEvents() {
_everlinkSdk.onEvent.listen((event) {
if (event is GeneratedTokenEvent) {
log('Generated token: Old - ${event.oldToken}, New - ${event.newToken}');
// 新生成的令牌,保存到数据库
} else if (event is DetectionEvent) {
doSomethingWithDetectedToken(event.detectedToken);
// 可以通过返回的令牌识别听到的位置/设备
}
}, onError: (error) {
log('Error receiving SDK event: $error');
showErrorDialog(context, error.toString());
});
}
Future<void> _everlinkStartDetecting() async {
try {
await _everlinkSdk.startDetecting();
} catch (e) {
showErrorDialog(context, e.toString());
}
}
Future<void> _everlinkStopDetecting() async => await _everlinkSdk.stopDetecting();
Future<void> _everlinkNewToken(String date, [int? validityPeriod]) async {
try {
await _everlinkSdk.newToken(date, validityPeriod);
} on EverlinkError catch (e) {
showErrorDialog(context, e.toString());
} catch (e) {
showErrorDialog(context, e.toString());
}
}
Future<void> _everlinkSaveTokens(List<String> tokens) async {
try {
await _everlinkSdk.saveTokens(tokens);
} catch (e) {
showErrorDialog(context, e.toString());
}
}
Future<void> _everlinkClearTokens() async => await _everlinkSdk.clearTokens();
Future<void> _everlinkStartEmitting() async {
try {
await _everlinkSdk.startEmitting();
} catch (e) {
showErrorDialog(context, e.toString());
}
}
Future<void> _everlinkStartEmittingToken(String token) async {
try {
await _everlinkSdk.startEmittingToken(token);
} catch (e) {
showErrorDialog(context, e.toString());
}
}
Future<void> _everlinkStopEmitting() async => await _everlinkSdk.stopEmitting();
Future<void> _everlinkPlayVolume(double volume, bool loudSpeaker) async => await _everlinkSdk.playVolume(volume, loudSpeaker);
void showErrorDialog(BuildContext context, String errorMessage) {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: const Text('Error'),
content: Text(errorMessage),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Okay'),
),
],
),
);
}
[@override](/user/override)
void dispose() {
// 释放资源
_everlinkSdk.dispose();
super.dispose();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: _currentBackgroundColor,
appBar: AppBar(
backgroundColor: const Color.fromRGBO(38, 40, 74, 1.0),
title: const Text('Everlink 插件',
style: TextStyle(
color: Colors.white,
)),
),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 4.0),
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('使用 Everlink 插件的示例项目',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 22,
color: Colors.white,
)),
const SizedBox(
height: 10,
),
TriggerButton(
buttonColor: _buttonColor,
title: '开始检测',
onPressed: () async {
setState(
() => _currentBackgroundColor = _defaultBackgroundColor,
);
await _everlinkStartDetecting();
}),
TriggerButton(
buttonColor: _buttonColor,
title: '停止检测',
onPressed: () async => await _everlinkStopDetecting()),
TriggerButton(
buttonColor: _buttonColor,
title: '新令牌',
onPressed: () async {
const date = "";
await _everlinkNewToken(date);
}),
TriggerButton(
buttonColor: _buttonColor,
title: '保存令牌',
onPressed: () async {
const tokensList = [
'evpan77f29450f255e956b27b7757d9f7348a',
'evpan77f29450f255e956b27b7757d9f7348a'
];
await _everlinkSaveTokens(tokensList);
}),
TriggerButton(
buttonColor: _buttonColor,
title: '清除令牌',
onPressed: () async => await _everlinkClearTokens()),
TriggerButton(
buttonColor: _buttonColor,
title: '开始发射',
onPressed: () async => await _everlinkStartEmitting()),
TriggerButton(
buttonColor: _buttonColor,
title: '发射令牌',
onPressed: () async {
const token = "evpan77f29450f255e956b27b7757d9f7348a";
await _everlinkStartEmittingToken(token);
}),
TriggerButton(
buttonColor: _buttonColor,
title: '停止发射',
onPressed: () async => await _everlinkStopEmitting(),
),
TriggerButton(
buttonColor: _buttonColor,
title: '播放音量',
onPressed: () async {
const volume = 0.8;
const useLoudSpeaker = true;
await _everlinkPlayVolume(volume, useLoudSpeaker);
}),
],
),
),
),
),
);
}
// 这里您可以使用返回的令牌来验证此用户
void doSomethingWithDetectedToken(String token) {
// 更改背景颜色
setState(
() => _currentBackgroundColor = _doSomethingBackgroundColor,
);
// 显示对话框
showDialog(
context: context,
// 标记为非可取消以基于时间进行取消
barrierDismissible: false,
builder: (context) {
// 这个方法将在一秒后调用并取消警报对话框
// 调整秒数从这里开始
Future.delayed(const Duration(seconds: 5)).whenComplete(
() => Navigator.pop(context),
);
return AlertDialog(
backgroundColor: _doSomethingBackgroundColor,
title: const Text(
'用户已检测!',
style: TextStyle(
fontSize: 24,
),
),
content: Text(
token,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 24,
),
),
);
},
);
}
}
// 一个单独的Widget类用于一组类似的Elevated按钮
class TriggerButton extends StatelessWidget {
const TriggerButton(
{super.key,
required this.buttonColor,
required this.onPressed,
required this.title});
final Color buttonColor;
final void Function() onPressed;
final String title;
[@override](/user/override)
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0),
child: ElevatedButton(
style: ButtonStyle(
fixedSize: WidgetStatePropertyAll(
Size(MediaQuery.of(context).size.width * 0.5, 42)),
backgroundColor: WidgetStatePropertyAll(
buttonColor,
),
),
onPressed: onPressed,
child: Text(
title,
style: const TextStyle(color: Colors.white),
),
),
);
}
}
更多关于Flutter集成Everlink服务插件everlink_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter集成Everlink服务插件everlink_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter项目中集成Everlink服务插件 everlink_sdk
的过程可以通过以下步骤来实现。这里假设你已经有一个Flutter项目,并且具备基本的Flutter开发知识。以下是一个详细的代码案例,展示了如何在Flutter项目中集成和使用 everlink_sdk
。
1. 添加依赖
首先,在你的 pubspec.yaml
文件中添加 everlink_sdk
的依赖:
dependencies:
flutter:
sdk: flutter
everlink_sdk: ^latest_version # 请替换为实际的最新版本号
然后运行 flutter pub get
来获取依赖。
2. 配置iOS和Android平台
根据 everlink_sdk
的文档,你可能需要在 iOS
和 Android
平台上进行一些配置。这里假设这些配置已经在Everlink的官方文档中详细说明,并且你已经按照文档完成了配置。
3. 初始化Everlink SDK
在你的Flutter应用的入口文件(通常是 main.dart
)中初始化 everlink_sdk
。
import 'package:flutter/material.dart';
import 'package:everlink_sdk/everlink_sdk.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
_initEverlink();
}
Future<void> _initEverlink() async {
try {
// 替换为你的Everlink API Key和Secret
String apiKey = 'your_everlink_api_key';
String apiSecret = 'your_everlink_api_secret';
// 初始化SDK
await EverlinkSdk.initialize(apiKey: apiKey, apiSecret: apiSecret);
// 你可以在这里添加其他初始化代码,比如检查用户登录状态等
print('Everlink SDK initialized successfully.');
} catch (e) {
print('Failed to initialize Everlink SDK: $e');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Everlink SDK Integration'),
),
body: Center(
child: Text('Check the console for Everlink SDK initialization status.'),
),
),
);
}
}
4. 使用Everlink SDK的功能
一旦SDK初始化成功,你就可以使用SDK提供的各种功能了。以下是一个示例,展示了如何使用Everlink SDK进行用户登录:
// 假设你有一个按钮触发登录操作
ElevatedButton(
onPressed: () async {
try {
// 替换为实际的用户名和密码
String username = 'user@example.com';
String password = 'password123';
// 执行登录操作
EverlinkUser user = await EverlinkSdk.login(username: username, password: password);
// 登录成功后,你可以获取用户信息并做进一步处理
print('User logged in successfully: ${user.toJson()}');
} catch (e) {
print('Login failed: $e');
}
},
child: Text('Login'),
)
注意事项
- 请确保你使用的是最新版本的
everlink_sdk
。 - 在实际项目中,不要将API Key和Secret硬编码在代码中,而是使用环境变量或安全的密钥管理服务。
- 根据
everlink_sdk
的API文档,可能会有更多的配置和功能,这里只展示了基本的初始化和登录流程。
通过以上步骤,你应该能够在Flutter项目中成功集成并使用 everlink_sdk
。如果你遇到任何问题,请参考 everlink_sdk
的官方文档或寻求Everlink的技术支持。