Flutter步数统计插件daily_pedometer的使用

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

Flutter步数统计插件daily_pedometer的使用

每日步数统计在健康管理中非常重要。本文将介绍如何使用daily_pedometer插件来实现这一功能。该插件目前仅支持Android平台。

权限设置

为了使daily_pedometer插件正常工作,你需要在项目的AndroidManifest.xml文件中添加以下权限:

<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>

示例用法

你可以查看示例应用以获得一个完整的例子。下面是一个更通用的例子。记得设置所需的权限,这可能需要你在手机的“设置”中手动允许。

import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:daily_pedometer/daily_pedometer.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await initializeService();
  runApp(const MyApp());
}

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

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

class _MyAppState extends State<MyApp> {
  String _platformVersion = '未知';

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

  // 初始化平台状态
  Future<void> initPlatformState() async {
    final pedometer = DailyPedometer();
    await pedometer.initialize(false);
    setState(() {
      _platformVersion = " ${pedometer.steps} 步";
    });

    pedometer.dailyStepCountStream.listen((event) async {
      setState(() {
        print("stepCountStream : $event");
        _platformVersion = " $event 步";
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Text('运行于: $_platformVersion\n'),
        ),
      ),
    );
  }
}

const notificationChannelId = 'my_foreground';

Future<void> initializeService() async {
  if (!Platform.isAndroid) return;

  final service = FlutterBackgroundService();
  service.invoke("refreshSensorListener");

  // 创建通知通道
  const AndroidNotificationChannel channel = AndroidNotificationChannel(
    notificationChannelId, // id
    '我的前台服务', // 标题
    description: '此通道用于重要的通知。', // 描述
    importance: Importance.low, // 重要性必须为低或更高
  );

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  if (Platform.isIOS || Platform.isAndroid) {
    await flutterLocalNotificationsPlugin.initialize(
      const InitializationSettings(
        iOS: DarwinInitializationSettings(),
        android: AndroidInitializationSettings('ic_bg_service_small'),
      ),
    );
  }

  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  await service.configure(
    androidConfiguration: AndroidConfiguration(
      onStart: onStart,
      autoStart: true,
      isForegroundMode: true,
      notificationChannelId: notificationChannelId,
      initialNotificationTitle: '优秀服务',
      initialNotificationContent: '初始化',
      foregroundServiceNotificationId: 888,
    ),
    iosConfiguration: IosConfiguration(
      autoStart: true,
      onForeground: onStart,
    ),
  );
}

// 启动服务时调用
[@pragma](/user/pragma)('vm:entry-point')
void onStart(ServiceInstance service) async {
  DartPluginRegistrant.ensureInitialized();
  print("111111 : 11");
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) {
      print("111111 : 1");
      service.setAsForegroundService();
    });

    service.on('setAsBackground').listen((event) {
      print("111111 : 2");
      service.setAsBackgroundService();
    });
  }

  service.on('stopService').listen((event) {
    print("111111 : 3");
    service.stopSelf();
  });

  DailyPedometer pedometer = DailyPedometer();
  service.on("refreshSensorListener").listen((event) async {
    print("refreshSensorListener");
    await pedometer.refreshSensorListener();
  });

  if (service is AndroidServiceInstance) {
    await pedometer.initialize(true);
    print("DailyPedometer 前台服务 ${pedometer.steps}");

    flutterLocalNotificationsPlugin.show(
      888,
      '测试步数',
      '今天的步数: ${pedometer.steps}',
      const NotificationDetails(
        android: AndroidNotificationDetails(
            notificationChannelId, notificationChannelId,
            icon: 'ic_bg_service_small', ongoing: true),
      ),
    );

    pedometer.dailyStepCountStream.listen((event) async {
      print("DailyPedometer 前台服务 $event");
      flutterLocalNotificationsPlugin.show(
        888,
        '测试步数',
        '今天的步数: $event',
        const NotificationDetails(
          android: AndroidNotificationDetails(
              notificationChannelId, notificationChannelId,
              icon: 'ic_bg_service_small', ongoing: true),
        ),
      );
    });
  }
}

更多关于Flutter步数统计插件daily_pedometer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter步数统计插件daily_pedometer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用daily_pedometer插件来统计步数的示例代码。daily_pedometer插件允许你访问设备的步数传感器数据。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加daily_pedometer依赖:

dependencies:
  flutter:
    sdk: flutter
  daily_pedometer: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 请求权限

在Android和iOS设备上使用步数传感器需要请求相应的权限。

Android

AndroidManifest.xml中添加权限请求:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>

    <!-- 其他配置 -->

</manifest>

iOS

Info.plist中添加权限请求描述:

<key>NSMotionUsageDescription</key>
<string>我们需要访问您的运动数据来统计步数</string>

3. 使用插件获取步数

下面是一个简单的示例,展示如何使用daily_pedometer插件来获取并显示当天的步数。

import 'package:flutter/material.dart';
import 'package:daily_pedometer/daily_pedometer.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _steps = 0;

  @override
  void initState() {
    super.initState();
    _getSteps();
  }

  Future<void> _getSteps() async {
    try {
      bool hasPermission = await DailyPedometer.requestPermission();
      if (hasPermission) {
        int steps = await DailyPedometer.stepsToday();
        setState(() {
          _steps = steps;
        });
      } else {
        print("权限被拒绝");
      }
    } catch (e) {
      print("获取步数失败: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('步数统计'),
        ),
        body: Center(
          child: Text('今天的步数: $_steps'),
        ),
      ),
    );
  }
}

4. 运行应用

确保你已经连接了一个支持步数传感器的设备,然后运行应用:

flutter run

这个示例代码展示了如何请求步数传感器权限,获取并显示当天的步数。如果权限被拒绝,应用会打印一条消息到控制台。如果获取步数失败,也会打印错误信息。

请根据你的实际需求调整这个示例代码,比如添加更多的错误处理、UI元素或者定期更新步数等。

回到顶部