Flutter活动识别插件flutter_activity_recognition的使用
Flutter活动识别插件flutter_activity_recognition的使用
Features
- 可以请求活动识别权限。
- 可以订阅
ActivityStream
以实时监听活动。
Getting started
添加依赖
为了使用此插件,需在pubspec.yaml
文件中添加flutter_activity_recognition
作为依赖。例如:
dependencies:
flutter_activity_recognition: ^4.0.0
配置平台特定权限
Android配置
打开AndroidManifest.xml
文件,并在<manifest>
和<application>
标签之间添加以下权限:
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
iOS配置
打开ios/Runner/Info.plist
文件,并在<dict>
标签内添加以下权限:
<key>NSMotionUsageDescription</key>
<string>Used to recognize user activity information.</string>
How to use
检查并请求权限
检查用户是否授予了活动识别权限,如果未授予,则请求权限。
Future<bool> _checkAndRequestPermission() async {
ActivityPermission permission =
await FlutterActivityRecognition.instance.checkPermission();
if (permission == ActivityPermission.PERMANENTLY_DENIED) {
// 权限已被永久拒绝
return false;
} else if (permission == ActivityPermission.DENIED) {
permission =
await FlutterActivityRecognition.instance.requestPermission();
if (permission != ActivityPermission.GRANTED) {
// 权限被拒绝
return false;
}
}
return true;
}
实时监听活动
使用activityStream
属性来实时监听活动。
StreamSubscription<Activity>? _activitySubscription;
Future<void> _subscribeActivityStream() async {
if (await _checkAndRequestPermission()) {
_activitySubscription = FlutterActivityRecognition.instance.activityStream
.handleError(_onError)
.listen(_onActivity);
}
}
void _onActivity(Activity activity) {
print('activity detected >> ${activity.toJson()}');
}
void _onError(dynamic error) {
print('error >> $error');
}
示例Demo
这是一个完整的示例代码,演示了如何使用flutter_activity_recognition
插件来监听用户的活动。
import 'dart:async';
import 'dart:developer' as dev;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_activity_recognition/flutter_activity_recognition.dart';
void main() => runApp(ExampleApp());
class ExampleApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => _ExampleAppState();
}
class _ExampleAppState extends State<ExampleApp> {
final ValueNotifier<ActivityResult?> _activityResult = ValueNotifier(null);
StreamSubscription<Activity>? _activitySubscription;
Future<void> _requestPermission() async {
ActivityPermission permission =
await FlutterActivityRecognition.instance.checkPermission();
if (permission == ActivityPermission.PERMANENTLY_DENIED) {
throw Exception('permission has been permanently denied.');
} else if (permission == ActivityPermission.DENIED) {
permission =
await FlutterActivityRecognition.instance.requestPermission();
if (permission != ActivityPermission.GRANTED) {
throw Exception('permission is ${permission.name}.');
}
}
}
void _startService() async {
try {
await _requestPermission();
// 订阅活动流
_activitySubscription = FlutterActivityRecognition.instance.activityStream
.handleError(_onError)
.listen(_onActivity);
} catch (error) {
_onError(error);
}
}
void _onActivity(Activity activity) {
dev.log('activity detected >> ${activity.toJson()}');
_activityResult.value = ActivityResult.success(activity);
}
void _onError(dynamic error) {
String errorMessage;
if (error is PlatformException) {
errorMessage = error.message ?? error.code;
} else {
errorMessage = error.toString();
}
dev.log('error >> $errorMessage');
_activityResult.value = ActivityResult.error(errorMessage);
}
@override
void initState() {
super.initState();
_startService();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter Activity Recognition'),
centerTitle: true,
),
body: _buildContentView(),
),
);
}
Widget _buildContentView() {
return ValueListenableBuilder(
valueListenable: _activityResult,
builder: (context, result, _) {
return ListView(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.all(8.0),
children: _buildListViewItems(result),
);
},
);
}
List<Widget> _buildListViewItems(ActivityResult? result) {
if (result == null) {
return [
Text('waiting for activity..'),
];
}
final String? error = result.error;
if (error != null) {
return [
Text('time: ${DateTime.now()}'),
Text('error: $error'),
];
}
return [
Text('time: ${DateTime.now()}'),
Text('type: ${result.data?.type}'),
Text('confidence: ${result.data?.confidence}'),
];
}
@override
void dispose() {
_activitySubscription?.cancel();
_activityResult.dispose();
super.dispose();
}
}
class ActivityResult {
ActivityResult._private({this.data, this.error});
final Activity? data;
final String? error;
factory ActivityResult.success(Activity data) =>
ActivityResult._private(data: data);
factory ActivityResult.error(String error) =>
ActivityResult._private(error: error);
}
Background Mode
如果您希望在后台使用此插件,请使用flutter_foreground_task
插件。
More Documentation
Support
如果您在使用插件时遇到任何bug或问题,请在GitHub上注册问题。您也可以通过邮箱联系我们:hwj930513@naver.com。
更多关于Flutter活动识别插件flutter_activity_recognition的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter活动识别插件flutter_activity_recognition的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个使用 flutter_activity_recognition
插件的简单示例,包括插件的安装、权限请求、以及基本的活动识别功能。
1. 安装插件
首先,你需要在 pubspec.yaml
文件中添加 flutter_activity_recognition
插件:
dependencies:
flutter:
sdk: flutter
flutter_activity_recognition: ^x.y.z # 请替换为最新版本号
然后运行以下命令来安装插件:
flutter pub get
2. 配置 Android 权限
在 android/app/src/main/AndroidManifest.xml
文件中添加必要的权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.BODY_SENSORS"/>
<application
... >
...
</application>
</manifest>
3. 请求权限并启动活动识别
接下来,在你的 Dart 代码中请求权限并启动活动识别。下面是一个完整的示例:
import 'package:flutter/material.dart';
import 'package:flutter_activity_recognition/flutter_activity_recognition.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ActivityRecognitionScreen(),
);
}
}
class ActivityRecognitionScreen extends StatefulWidget {
@override
_ActivityRecognitionScreenState createState() => _ActivityRecognitionScreenState();
}
class _ActivityRecognitionScreenState extends State<ActivityRecognitionScreen> {
ActivityRecognition? _activityRecognition;
ActivityRecognitionResult? _latestResult;
@override
void initState() {
super.initState();
_activityRecognition = ActivityRecognition();
_requestPermissions();
}
void _requestPermissions() async {
if (await Permission.activityRecognition.status != PermissionStatus.granted) {
Map<Permission, PermissionStatus> statuses = await Permission.activityRecognition
.request();
if (statuses[Permission.activityRecognition] == PermissionStatus.granted) {
_startActivityRecognition();
} else {
// 权限被拒绝,处理逻辑
}
} else {
_startActivityRecognition();
}
}
void _startActivityRecognition() {
_activityRecognition?.startActivityRecognitionUpdates(
interval: 1000, // 每秒更新一次
distanceFilter: 0,
onResult: (ActivityRecognitionResult result) {
setState(() {
_latestResult = result;
});
print("Detected Activity: ${result.activity}");
print("Confidence: ${result.confidence}");
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Activity Recognition'),
),
body: Center(
child: _latestResult != null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Detected Activity: ${_latestResult!.activity}'),
Text('Confidence: ${_latestResult!.confidence}'),
],
)
: Text('Waiting for activity recognition...'),
),
);
}
@override
void dispose() {
_activityRecognition?.stopActivityRecognitionUpdates();
super.dispose();
}
}
4. 依赖项
注意,上述代码还使用了 permission_handler
插件来处理权限请求。你需要在 pubspec.yaml
文件中添加它:
dependencies:
flutter:
sdk: flutter
flutter_activity_recognition: ^x.y.z # 请替换为最新版本号
permission_handler: ^x.y.z # 请替换为最新版本号
运行以下命令来安装 permission_handler
插件:
flutter pub get
总结
以上代码展示了如何使用 flutter_activity_recognition
插件进行活动识别,包括权限请求、启动活动识别更新以及处理识别结果。你可以根据实际需求对代码进行进一步修改和扩展。