+
Skip to content

Conversation

mateussiqueira
Copy link

@mateussiqueira mateussiqueira commented Mar 24, 2025

Não revise, ainda estou implementando melhorias

Background Location Plugin

A Flutter plugin for getting location updates in the background on Android and iOS. This plugin provides a simple way to get location updates even when the app is in the background.

Features

  • Continuous location updates in the background
  • High accuracy location tracking
  • Battery efficient implementation
  • Support for both Android and iOS
  • Permission handling
  • Error handling and recovery
  • Location data caching
  • Configurable accuracy levels

Installation

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

dependencies:
  background_location:
    git:
      url: https://github.com/mateussiqueira/background_location.git

Android Setup

Add the following permissions to your android/app/src/main/AndroidManifest.xml file:

<manifest ...>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <application ...>
        <service
            android:name="com.mateussiqueira.background_location.BackgroundLocationService"
            android:foregroundServiceType="location"
            android:exported="false" />
    </application>
</manifest>

Also, make sure your android/app/build.gradle has the minimum SDK version set to 21 or higher:

android {
    defaultConfig {
        minSdkVersion 21
        ...
    }
}

iOS Setup

Add the following keys to your ios/Runner/Info.plist file:

<dict>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>This app needs access to location when open to track your position.</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>This app needs access to location when in the background to track your position.</string>
    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>This app needs access to location when open and in the background to track your position.</string>
    <key>UIBackgroundModes</key>
    <array>
        <string>location</string>
    </array>
</dict>

Usage

Here's a simple example of how to use the plugin:

import 'package:background_location/background_location.dart';

// Request permissions
bool hasPermission = await BackgroundLocation.requestPermissions();
if (!hasPermission) {
  print('Location permissions not granted');
  return;
}

// Start location service
bool started = await BackgroundLocation.startLocationService();
if (!started) {
  print('Failed to start location service');
  return;
}

// Listen to location updates
BackgroundLocation.locationStream.listen((location) {
  print('Location: ${location.latitude}, ${location.longitude}');
}, onError: (error) {
  print('Error getting location: $error');
});

// Stop location service when done
await BackgroundLocation.stopLocationService();

Error Handling

The plugin provides error handling through try-catch blocks and error callbacks:

try {
  await BackgroundLocation.startLocationService();
} catch (e) {
  print('Error starting location service: $e');
}

// Using error callback in stream
BackgroundLocation.locationStream.listen(
  (location) {
    print('Location: ${location.latitude}, ${location.longitude}');
  },
  onError: (error) {
    print('Error getting location: $error');
    // Handle error (e.g., retry, show user message)
  },
);

Location Data Caching

The plugin automatically caches the last known location. You can access it using:

LocationData? lastLocation = await BackgroundLocation.getLastKnownLocation();
if (lastLocation != null) {
  print('Last known location: ${lastLocation.latitude}, ${lastLocation.longitude}');
}

Configuring Accuracy

You can configure the location accuracy when starting the service:

await BackgroundLocation.startLocationService(
  accuracy: LocationAccuracy.high, // Options: low, medium, high
);

API Reference

Methods

  • startLocationService({LocationAccuracy accuracy = LocationAccuracy.high}): Starts the location service
  • stopLocationService(): Stops the location service
  • isLocationServiceRunning(): Checks if the location service is running
  • requestPermissions(): Requests location permissions
  • checkPermissions(): Checks if location permissions are granted
  • getLastKnownLocation(): Gets the last known location from cache

Stream

  • locationStream: A stream of LocationData objects containing:
    • latitude: The latitude of the location
    • longitude: The longitude of the location
    • accuracy: The accuracy of the location in meters
    • altitude: The altitude of the location in meters
    • speed: The speed of the device in meters per second
    • speedAccuracy: The accuracy of the speed in meters per second
    • heading: The heading of the device in degrees
    • time: The timestamp of the location update

Troubleshooting

Common Issues

  1. Location updates not working in background

    • Ensure all required permissions are granted
    • Check if battery optimization is disabled for your app
    • Verify background location permission is granted on Android 10+
  2. High battery consumption

    • Use appropriate accuracy level (lower accuracy = less battery usage)
    • Implement proper error handling to stop service when needed
    • Consider implementing a geofencing solution for specific use cases
  3. Permission issues

    • Check if all required permissions are in AndroidManifest.xml
    • Verify Info.plist keys are properly configured on iOS
    • Handle permission denial gracefully in your app

Debug Mode

Enable debug mode to get detailed logs:

await BackgroundLocation.startLocationService(debug: true);

Example App

Check out the example directory for a complete implementation.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

This project is licensed under the MIT License - see the LICENSE file for details.

…Android implementation using FusedLocationProviderClient - Add iOS implementation using CoreLocation - Add LocationData model for location updates - Add permission handling for both platforms - Add example app with location tracking UI - Add comprehensive test suite - Update documentation with setup instructions
…te files - Add location accuracy configuration - Add location caching - Improve error handling - Update documentation with examples and troubleshooting
…ntation from com.almoullim package - Keep newer implementation from com.mateussiqueira package
…ts in example app - Remove references to deleted files
…les - Update test cases for new API methods - Remove unused test cases
…s to use correct API - Fix EventChannel handling in tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载