Skip to content

Unlocking the Power of Mobile Sensing with CARP Mobile Sensing Framework in Flutter

In the rapidly evolving world of mobile app development, the ability to collect and analyze sensor data has become increasingly important. Whether you’re building health apps, fitness trackers, or context-aware applications, the CARP Mobile Sensing (CAMS) framework is a powerful tool that can significantly enhance your Flutter projects. Today, we’ll dive deep into the carp_mobile_sensing package and explore how it can revolutionize your approach to mobile sensing.

What is CARP Mobile Sensing?

CARP Mobile Sensing is a comprehensive framework designed for cross-platform (iOS and Android) mobile sensing in Flutter. It provides a robust infrastructure for collecting, processing, and managing sensor data from mobile devices. The framework is part of the larger CARP (Copenhagen Center for Health Technology) ecosystem, which focuses on digital health and sensing technologies.

Getting Started with carp_mobile_sensing

To begin using the CARP Mobile Sensing framework in your Flutter project, you’ll need to add the carp_mobile_sensing package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  carp_core: ^latest
  carp_mobile_sensing: ^latest

After adding the dependencies, run flutter pub get to fetch the packages.

Configuring Your App

Before diving into the code, there are a few configuration steps you need to take to ensure CAMS works correctly in your app.

Android Configuration

  1. Set the minimum Android SDK to 26 and Java SDK Version to 34 in your android/app/build.gradle file:
android {
    compileSdkVersion 34

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        minSdkVersion 26
        targetSdkVersion flutter.targetSdkVersion
    }
}
  1. Add necessary permissions to your android/app/src/main/AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"
        android:maxSdkVersion="32" />
  1. Add the following receivers to your AndroidManifest.xml file within the <application> tags:
<receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
<receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
    </intent-filter>
</receiver>

iOS Configuration

For iOS, add the following to your ios/Runner/Info.plist file:

<key>NSMotionUsageDescription</key>
<string>This application tracks your steps</string>

Creating a Simple Sensing Study

Now that we’ve set up our project, let’s create a simple sensing study using CAMS. This example will collect step counts, ambient light, screen events, and battery state.

import 'package:carp_mobile_sensing/carp_mobile_sensing.dart';

void main() async {
  // Initialize the framework
  await CarpMobileSensing.instance.initialize();

  // Define the primary device (smartphone)
  final phone = Smartphone();

  // Create a study protocol
  final protocol = SmartphoneStudyProtocol(
    ownerId: 'researcher@example.com',
    name: 'Basic Sensing Study',
    dataEndPoint: SQLiteDataEndPoint(),
  )
    ..addPrimaryDevice(phone)
    ..addTaskControl(
      DelayedTrigger(delay: const Duration(seconds: 10)),
      BackgroundTask(measures: [
        Measure(type: SensorSamplingPackage.STEP_COUNT),
        Measure(type: SensorSamplingPackage.AMBIENT_LIGHT),
        Measure(type: DeviceSamplingPackage.SCREEN_EVENT),
        Measure(type: DeviceSamplingPackage.BATTERY_STATE),
      ]),
      phone,
      Control.Start,
    );

  // Deploy and start the study
  await SmartPhoneClientManager().configure();
  await SmartPhoneClientManager().addStudyProtocol(protocol);
  await SmartPhoneClientManager().start();

  // Listen to the data stream
  SmartPhoneClientManager().measurements.listen((measurement) {
    print('Received measurement: ${measurement.toJson()}');
  });
}

This example sets up a basic sensing study that collects step count, ambient light, screen events, and battery state. The study starts after a 10-second delay and stores data locally using SQLite.

Advanced Features and Extensibility

CAMS is designed to be highly extensible. Here are some ways you can extend its functionality:

  1. Create custom sampling packages: Implement your own SamplingPackage to add new sensing capabilities.

  2. Implement custom data endpoints: Create your own DataEndPoint and DataManager to store or transmit data to custom backends or services.

  3. Develop transformer schemas: Implement TransformerSchema to transform CARP data into other formats or apply privacy-preserving techniques.

  4. Customize UI components: Create custom widgets and screens to visualize and interact with the collected data.

Best Practices and Considerations

When working with CAMS, keep the following best practices in mind:

  1. Battery Usage: Be mindful of the impact on battery life, especially when sampling frequently or using power-intensive sensors.

  2. Privacy: Ensure you have appropriate user consent and handle sensitive data securely.

  3. Data Management: Implement proper data management strategies, including data retention policies and secure data transmission.

  4. Error Handling: Implement robust error handling to manage sensor unavailability or permission issues.

  5. Testing: Thoroughly test your sensing study on various devices and Android/iOS versions to ensure compatibility.

Conclusion

The CARP Mobile Sensing framework opens up a world of possibilities for Flutter developers interested in mobile sensing applications. Whether you’re building health monitoring apps, context-aware services, or research tools, CAMS provides a solid foundation for collecting and managing sensor data.

By leveraging the power of CAMS, you can focus on building innovative applications that harness the rich sensor data available on modern smartphones, without getting bogged down in the complexities of low-level sensor APIs and data management.

Remember to check out the CAMS wiki for more detailed documentation and stay updated with the latest features and best practices in mobile sensing with Flutter.

Happy sensing!


This blog post provides a comprehensive overview of the CARP Mobile Sensing framework, focusing on the carp_mobile_sensing package. It covers installation, configuration, basic usage, and advanced features. The post also includes internal links to relevant categories and external links to official documentation and resources.

Leave a Reply

Your email address will not be published. Required fields are marked *