0% found this document useful (0 votes)
50 views36 pages

07-Module 7

Uploaded by

Habiba Yasser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views36 pages

07-Module 7

Uploaded by

Habiba Yasser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

CSE431

Mobile Programming

MODULE 7:
Sensors, Location, and Google Maps
Sensors
sensors_plus Flutter Package
• A Flutter plugin to access the accelerometer,
gyroscope, magnetometer and barometer
sensors.
sensors_plus Requirements
• Flutter >=3.19.0
• Dart >=3.3.0 <4.0.0
• iOS >=12.0
• MacOS >=10.14
• Android compileSDK 34
• Java 17
• Android Gradle Plugin >=8.3.0
• Gradle wrapper >=8.4
Add sensors_plus to your Flutter app
• Add sensors_plus as a dependency in your pubspec.yaml file.

• On iOS you must also include a key called NSMotionUsageDescription in your


app's Info.plist file. This key provides a message that tells the user why the app
is requesting access to the device’s motion data. The plugin itself needs access
to motion data to get barometer data.

Example Info.plist entry:

<key>NSMotionUsageDescription</key>
<string>This app requires access to the barometer to provide altitude
information.</string>

• Caution
• Adding NSMotionUsageDescription is a requirement and not doing so will
crash your app when it attempts to access motion data.
Sensor Classes
• UserAccelerometerEvent describes the acceleration of the
device, in m/s2. If the device is still, or is moving along a
straight line at constant speed, the reported acceleration is
zero. If the device is moving e.g. towards north and its speed is
increasing, the reported acceleration is towards north; if it is
slowing down, the reported acceleration is towards south; if it
is turning right, the reported acceleration is towards east. The
data of this stream is obtained by filtering out the effect of
gravity from AccelerometerEvent.

• AccelerometerEvent describes the acceleration of the


device, in m/s2, including the effects of gravity. Unlike
UserAccelerometerEvent, this stream reports raw data from
the accelerometer (physical sensor embedded in the mobile
device) without any post-processing. The accelerometer is
unable to distinguish between the effect of an accelerated
movement of the device and the effect of the surrounding
gravitational field. This means that, at the surface of Earth,
even if the device is completely still, the reading of
AccelerometerEvent is an acceleration of intensity 9.8
directed upwards (the opposite of the graviational
acceleration). This can be used to infer information about the
position of the device (horizontal/vertical/tilted).
AccelerometerEvent reports zero acceleration if the device is
free falling.
GyroscopeEvent
describes the
rotation of the
device.

Sensor
Classes
Sensor
Classes
Sensor
Classes
Add BroadcastStream to your Flutter app

• These events are exposed through a


BroadcastStream:
• accelerometerEvents,
• userAccelerometerEvents,
• gyroscopeEvents,
• magnetometerEvents, and
• barometerEvents, respectively.
Note
Some low end or old Android devices don't have all sensors available. Plugin
won't crash the app, but it is highly recommended to add onError() to handle
such cases gracefully.
Add Sensors to your Flutter app
import 'package:sensors_plus/sensors_plus.dart'; onError: (error) {
// Logic to handle error
accelerometerEvents.listen( // Needed for Android in case sensor is not available
(AccelerometerEvent event) { },
print(event); cancelOnError: true,
}, );
onError: (error) { // [GyroscopeEvent (x: 0.0, y: 0.0, z: 0.0)]
// Logic to handle error
// Needed for Android in case sensor is not available magnetometerEvents.listen(
}, (MagnetometerEvent event) {
cancelOnError: true, print(event);
); },
// [AccelerometerEvent (x: 0.0, y: 9.8, z: 0.0)] onError: (error) {
// Logic to handle error
userAccelerometerEvents.listen( // Needed for Android in case sensor is not available
(UserAccelerometerEvent event) { },
print(event); cancelOnError: true,
}, );
onError: (error) { // [MagnetometerEvent (x: -23.6, y: 6.2, z: -34.9)]
// Logic to handle error
// Needed for Android in case sensor is not available barometerEvents.listen(
}, (BarometerEvent event) {
cancelOnError: true, print(event);
); },
// [UserAccelerometerEvent (x: 0.0, y: 0.0, z: 0.0)] onError: (error) {
// Logic to handle error
gyroscopeEvents.listen( // Needed for Android in case sensor is not available
(GyroscopeEvent event) { },
print(event); cancelOnError: true,
}, );
// [BarometerEvent (pressure: 1000.0)]
Add Sensors to your Flutter app
• Alternatively, every stream allows to specify the sampling rate for its
sensor using one of predefined constants or using a custom value.

magnetometerEvents(samplingPeriod:
SensorInterval.normalInterval).listen(
(MagnetometerEvent event) { Note
On Android it is not guaranteed that events from sensors will arrive
print(event); with specified sampling rate as it is noted in the official Android
}, documentation (see the description for the samplingPeriodUs
parameter). In reality delay varies depending on Android version,
onError: (error) { device hardware and vendor's OS customizations.
// Logic to handle error
// Needed for Android in case sensor is not available
},
cancelOnError: true,
);
Add Sensors to your Flutter app
Platform Restrictions and Considerations

The following lists the restrictions for the sensors on certain platforms due to
limitations of the platform.

• Magnetometer and Barometer missing for web


The Magnetometer API is currently not supported by any modern web browsers.
Check browser compatibility matrix on MDN* docs for Magnetormeter API.

• Currently it is not possible to set sensors sampling rate on web. Calls to event streams
at specied sampling periods will have the sampling period ignored.

• Barometer sampling period limitation for iOS


On iOS devices, barometer updates are CMAltimeter which provides updates at
regular intervals that cannot be controlled by the user. Calls to
barometerEventStream at specied sampling periods will have the sampling period
ignored.

Developers should consider alternative methods or inform users about the limitation when
their application runs on a web platform.
*Mozilla Developer Network (MDN), is a documentation repository and learning resource for web developers.
Add Sensors to your Flutter app

Reference for installation and Examples

https://pub.dev/packages/sensors_plus/install
Location

15
Build location-aware apps

• One of the unique features of mobile applications is


location awareness.
• Mobile users take their devices with them everywhere,
and adding location awareness to your app offers users
a more contextual experience.
• The location APIs available in Google Play services
facilitate adding location awareness to your app with
automated location tracking, wrong-side-of-the-street
detection, geofencing, and activity recognition.
Location Permissions
To protect user privacy, apps that use location services must request
location permissions.

• Types of location access


Each permission has a combination of the following
characteristics:

• Category: Either foreground location or background


location.

• Accuracy: Either precise location or approximate


location.
Location Permissions
• If your app contains a feature that shares or
receives location information only once, or for a
defined amount of time, then that feature
requires foreground location access.

• An app requires background location access if a


feature within the app constantly shares location
with other users or uses the Geofencing API.
Location Accuracy
Location plugins
• Flutter location plugin

• Flutter Geolocator Plugin


Flutter Location Plugin

21
Add Location to your Flutter app
• The location plugin for Flutter handles getting
a location on Android and iOS. It also provides
callbacks when the location is changed.

Add this to your package's pubspec.yaml file:

dependencies:
location: ^5.0.0
Android
• To use location background mode on Android,
you have to use the
enableBackgroundMode({bool enable}) API
before accessing location in the background and
adding necessary permissions. You should place
Request the required permissions in your applications

Location • <uses-permission
android:name="android.permission.FOREGROUN
Permissions •
D_SERVICE" />
<uses-permission
android:name="android.permission.ACCESS_BAC
KGROUND_LOCATION"/>

• Remember that the user has to accept the


location permission to always allow to use the
background location. The Android 11 option to
always allow is not presented on the location
permission dialog prompt.
Request Location
Permissions
• Android

• The user has to enable it manually


from the app settings. This should be
explained to the user on a separate UI
that redirects the user to the app's
location settings managed by the
operating system. More on that topic
can be found on Android developer
pages.
iOS
to use it in iOS, you have to add this permission in Info.plist :

// This is probably the only one you need. Background location is


//supported by this -- the caveat is that a blue badge is shown in
//the status bar
// when the app is using location service while in the background.
Request NSLocationWhenInUseUsageDescription

// Deprecated, use
Location NSLocationAlwaysAndWhenInUseUsageDescription instead.
NSLocationAlwaysUsageDescription
Permissions // Use this very carefully. This key is required only if your iOS app
// uses APIs that access the user’s location information at all
times,
// even if the app isn't running.
NSLocationAlwaysAndWhenInUseUsageDescription

To receive location when application is in background, to Info.plist


you have to add property list key :

UIBackgroundModes

with string value:


location
Then you just have to import the package with

import 'package:location/location.dart’;

In order to request location, you should always check Location Service status
and Permission status manually

Location location = new Location();

bool _serviceEnabled;
PermissionStatus _permissionGranted;
LocationData _locationData;

_serviceEnabled = await location.serviceEnabled();


To use if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();

location if (!_serviceEnabled) {
return;
}
}

_permissionGranted = await location.hasPermission();


if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}

_locationData = await location.getLocation();


To use location
On Android, a foreground notification is
displayed with information that location
service is running in the background.

On iOS, while the app is in the background


and gets the location, the blue system bar
notifies users about updates. Tapping on
this bar moves the User back to the app.
Flutter Geolocator Plugin

28
Flutter Geolocator Plugin

A Flutter geolocation plugin which provides easy access to


platform specific location services
(FusedLocationProviderClient or if not available the
LocationManager on Android and CLLocationManager on iOS).
Flutter Geolocator Plugin

Features
• Get the last known location;
• Get the current location of the device;
• Get continuous location updates;
• Check if location services are enabled on the device;
• Calculate the distance (in meters) between two
geocoordinates;
• Calculate the bearing between two geocoordinates;

Reference:
https://pub.dev/packages/geolocator
1
import 'package:geolocator/geolocator.dart';

/// Determine the current position of the device.


///
/// When the location services are not enabled or permissions
Implementation /// are denied the `Future` will return an error.
Steps Future<Position> _determinePosition() async {
bool serviceEnabled;

2
LocationPermission permission;

// Test if location services are enabled.


serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}

3 permission = await Geolocator.checkPermission();


if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}

if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');

4 }

// When we reach here, permissions are granted and we can


// continue accessing the position of the device.
return await Geolocator.getCurrentPosition();
}
Request Permission at Run Time

32
Google Maps

33
Google Maps for Flutter
• Get an API key at https://cloud.google.com/maps-platform/.
• Enable Google Map SDK for each platform.
• Go to Google Developers Console.
• Choose the project that you want to enable Google Maps on.
• Select the navigation menu and then select "Google Maps".
• Select "APIs" under the Google Maps menu.
• To enable Google Maps for Android, select "Maps SDK for Android" in
the "Additional APIs" section, then select "ENABLE".
• To enable Google Maps for iOS, select "Maps SDK for iOS" in the
"Additional APIs" section, then select "ENABLE".
• To enable Google Maps for Web, enable the "Maps JavaScript API".
• Make sure the APIs you enabled are under the "Enabled APIs" section.

34
Adding
Google

Maps to a https://codelabs.de
velopers.google.co
m/codelabs/google
Flutter app -maps-in-flutter#0

35
End of Module 7

You might also like