Flutter运动数据追踪插件movesdk的使用
Flutter Move SDK
Flutter package for MOVE SDK - please see MOVE SDK Documentation for features and details about the MOVE SDK.
Installation
Add the Dolphin MOVE SDK package to your Flutter app using:
flutter pub add movesdk
Or, by adding it as a dependency to your pubspec.yaml
file and running:
flutter pub get
See Flutter Package and Plugin Usage for further information regarding package use.
import 'package:movesdk/movesdk.dart';
Android
The SDK needs to be initialized at the start of the app by calling MoveSdk.init
. It is recommended to put this in the Application’s onCreate
method. This will load the persistent Move SDK state.
import io.dolphin.move.MoveSdk
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
val sdk = MoveSdk.init(this)
// Additional initialization code can go here
}
}
iOS
Initialization happens automatically in appDidFinishLaunching
.
Support
For support, contact info@dolph.in.
License
The contents of this repository are licensed under the Apache License, version 2.0.
Example
Dolphin MOVE SDK Flutter Example
Reference: MOVE SDK Documentation.
An example for the Dolphin Move SDK Flutter plugin.
App Cycle
On app initialization, the SDK will be initialized automatically and store its persisted state.
Toggle Activation Switch: ON
- Creates a user for you if no user already exists.
- The SDK will be in the ready state, and the app will automatically start SDK services using the
startAutomaticDetection
API.
Toggle Activation Switch: OFF
- Stops the SDK services using the
stopAutomaticDetection
API. - As the sample app is using the
stopAutomaticDetection
API and notshutdown
, the SDK state will only transition to the ready state and not shut down. Hence, future toggles will only start SDK services without re-creating a user or re-initializing the SDK.
The SDK activation toggling state is persisted for future initializations.
To Run This Project
-
Request a product API Key by contacting Dolphin MOVE.
-
Insert API key “Bearer <YOUR_API_KEY>” in the appropriate place in the code.
-
Launch a device such as the iOS Simulator.
-
Using the terminal, run:
flutter run lib/io/dolphin/move/example/main.dart
Starting Point
SDK Setup
Authorization
After contacting us and getting a product API key, use it to fetch a MoveAuth
from the Move Server. The MoveAuth
object will be passed to the SDK on initialization and be used by the SDK to authenticate its services.
If the provided MoveAuth
was invalid, the SDK will not try to fetch a new auth through the auth expiry listener. Check the documentation for details.
The setup is persisted for the SDK to automatically continue when the app is relaunched from the background.
To unregister the user with the SDK, use the shutdown
method.
Configuration
MoveConfig
allows host apps to configure which of the licensed Move services should be enabled. It could be based on each user preference or set from a remote server. Services which do not have the required permissions may not run or only collect incomplete data.
Support
For support, contact info@dolph.in.
License
The contents of this repository are licensed under the Apache License, version 2.0.
Complete Example Code
Here is a complete example of how to use the MOVE SDK in a Flutter application:
pubspec.yaml
name: move_example
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
movesdk: ^1.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
lib/main.dart
import 'package:flutter/material.dart';
import 'package:movesdk/movesdk.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MOVE SDK Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MoveHomePage(),
);
}
}
class MoveHomePage extends StatefulWidget {
@override
_MoveHomePageState createState() => _MoveHomePageState();
}
class _MoveHomePageState extends State<MoveHomePage> {
bool _isActivated = false;
@override
void initState() {
super.initState();
_initializeSDK();
}
Future<void> _initializeSDK() async {
// Initialize the SDK with your API key
final moveAuth = MoveAuth(apiKey: 'Bearer YOUR_API_KEY');
await MoveSdk.init(moveAuth);
}
Future<void> _toggleActivation(bool value) async {
setState(() {
_isActivated = value;
});
if (value) {
await MoveSdk.startAutomaticDetection();
} else {
await MoveSdk.stopAutomaticDetection();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('MOVE SDK Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Toggle MOVE SDK Activation:',
),
Switch(
value: _isActivated,
onChanged: _toggleActivation,
),
],
),
),
);
}
}
android/app/src/main/kotlin/com/example/move_example/MainApplication.kt
package com.example.move_example
import android.app.Application
import io.dolphin.move.MoveSdk
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
val sdk = MoveSdk.init(this)
// Additional initialization code can go here
}
}
ios/Runner/AppDelegate.swift
Initialization happens automatically in appDidFinishLaunching
.
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
This example demonstrates how to initialize the MOVE SDK, toggle its activation, and handle basic UI interactions in a Flutter application. Make sure to replace 'Bearer YOUR_API_KEY'
with your actual API key.
更多关于Flutter运动数据追踪插件movesdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter运动数据追踪插件movesdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中集成并使用Movesense SDK(通常简称为MoveSDK)来进行运动数据追踪,实际上涉及到与Movesense设备的蓝牙通信。由于Movesense SDK本身是为原生Android和iOS开发的,因此直接在Flutter中使用它需要通过平台通道(Platform Channels)进行桥接。以下是一个简要的代码示例,展示如何在Flutter中设置平台通道与Movesense设备通信。
1. 设置Flutter项目
首先,确保你已经创建了一个Flutter项目。如果还没有,可以使用以下命令创建一个新的Flutter项目:
flutter create move_tracker
cd move_tracker
2. 添加平台特定代码
iOS部分
在ios/Runner
目录下,添加Movesense SDK的依赖和配置。这通常涉及到将Movesense SDK的框架添加到Xcode项目中,并设置相应的权限(如蓝牙权限)。
由于Movesense SDK的集成过程相对复杂,这里仅展示如何在Flutter与iOS原生代码之间建立通信。你需要在ios/Runner/AppDelegate.swift
中配置蓝牙权限,并在ios/
目录下创建一个新的Swift文件(例如MovesensePlugin.swift
),用于处理与Movesense设备的通信。
MovesensePlugin.swift
import Flutter
import CoreBluetooth
public class MovesensePlugin: NSObject, FlutterPlugin, CBCentralManagerDelegate {
private var channel: FlutterMethodChannel?
private var centralManager: CBCentralManager!
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "movesense_channel", binaryMessenger: registrar.messenger())
let instance = MovesensePlugin()
instance.channel = channel
registrar.addMethodCallDelegate(instance, channel: channel)
instance.centralManager = CBCentralManager(delegate: instance, queue: nil)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "scanForDevices" {
self.centralManager.scanForPeripherals(withServices: nil, options: nil)
result(nil)
} else {
result(FlutterMethodNotImplementedError(methodName: call.method))
}
}
// CBCentralManagerDelegate methods
func centralManagerDidUpdateState(_ central: CBCentralManager) {
// Handle central manager state changes
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// Handle discovered peripherals
let deviceInfo = ["name": peripheral.name ?? "Unknown", "identifier": peripheral.identifier.uuidString]
self.channel?.invokeMethod("deviceDiscovered", arguments: deviceInfo)
}
// Other CBCentralManagerDelegate methods...
}
Android部分
在android/
目录下,你需要配置AndroidManifest.xml以请求蓝牙权限,并创建一个新的Kotlin/Java类来处理与Movesense设备的通信。
MovesensePlugin.kt
package com.example.movetracker
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
class MovesensePlugin: FlutterPlugin, MethodCallHandler, ActivityAware {
private lateinit var channel: MethodChannel
private lateinit var bluetoothAdapter: BluetoothAdapter
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "movesense_channel")
channel.setMethodCallHandler(this)
val context = flutterPluginBinding.applicationContext
val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothAdapter = bluetoothManager.adapter
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "scanForDevices") {
if (bluetoothAdapter.isEnabled) {
// Implement Bluetooth scanning logic here
// For simplicity, just return success for now
result.success(null)
} else {
result.error("BLUETOOTH_DISABLED", "Bluetooth is disabled on this device.", null)
}
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
// ActivityAware methods...
}
3. 在Flutter中调用平台方法
最后,在Flutter的Dart代码中,你可以通过MethodChannel与原生代码进行通信。
main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
static const platform = const MethodChannel('movesense_channel');
@override
void initState() {
super.initState();
scanForDevices();
}
Future<void> scanForDevices() async {
try {
await platform.invokeMethod('scanForDevices');
} on PlatformException catch (e) {
print("Failed to scan for devices: '${e.message}'.");
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Movesense Plugin Demo'),
),
body: Center(
child: Text('Scanning for Movesense devices...'),
),
),
);
}
}
注意
上述代码仅展示了如何在Flutter与原生代码之间建立通信的基本框架,并没有包含Movesense SDK的具体实现细节。由于Movesense SDK的集成相对复杂,你需要参考Movesense的官方文档来完成SDK的集成和设备的具体通信逻辑。
此外,上述代码示例中的蓝牙扫描逻辑是简化的,实际项目中你需要处理扫描结果的回调,并将设备信息传递给Flutter前端。这通常涉及到在原生代码中监听蓝牙扫描回调,并通过MethodChannel将设备信息传递给Flutter。