background_locator 1.1.10+1

  • Readme
  • Changelog
  • Example
  • Installing
  • 95

background_locator pub package #

A Flutter plugin for getting location updates even when the app is killed.

demo

Refer to wiki page for install and setup instruction or jump to specific subject with below links:

License #

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

Contributor #

Thanks to all who contributed on this plugin to fix bugs and adding new feature, including:

1.1.10+1 #

  • Add region monitoring for iOS to get location info while app is terminated;
  • Minor iOS bug fix;
  • Add a way to use 3rd party plugins while app is terminated in iOS;

1.1.7+1 #

  • Add notification icon color;
  • Add isMocked property on location model;
  • Add channel name property on location dto;

1.1.5+1 #

  • Fix crash in onStartCommand caused by null intent on Android;
  • Fix getting several unwanted position on iOS;

1.1.3+1 #

  • Add possibility to restart locator service after reboot;
  • Fix triggering android notification callback with wrong notification;

1.1.2+2 #

  • Fix optional android notification callback.

1.1.2+1 #

  • Fix accessing other plugins when app is terminated.

1.1.1+1 #

  • ‌Fix Callback is not triggered in iOS.

1.1.0+1 #

  • Add callback for android notification.

1.0.1+2 #

  • Fix crash on detach.

1.0.1+1 #

  • Add isRegistered method.
  • Bug fixes.

1.0.0+1 #

  • Add auto stop feature.
  • Update flutter plugin library to version 2.

0.0.4-beta #

  • Add parameter to setting to change android wakelock time.
  • Prevent service from registering twice.

0.0.3-beta #

Change where location access requested.

0.0.2-beta #

  • Improvements.

0.0.1-beta #

  • initial release.

example/lib/main.dart

import 'dart:async';
import 'dart:isolate';
import 'dart:ui';

import 'package:background_locator/background_locator.dart';
import 'package:background_locator/location_dto.dart';
import 'package:background_locator/location_settings.dart';
import 'package:flutter/material.dart';
import 'package:location_permissions/location_permissions.dart';

import 'file_manager.dart';
import 'location_callback_handler.dart';
import 'location_service_repository.dart';

void main() => runApp(MyApp());

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

class _MyAppState extends State<MyApp> {
  ReceivePort port = ReceivePort();

  String logStr = '';
  bool isRunning;
  LocationDto lastLocation;
  DateTime lastTimeLocation;

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

    if (IsolateNameServer.lookupPortByName(
            LocationServiceRepository.isolateName) !=
        null) {
      IsolateNameServer.removePortNameMapping(
          LocationServiceRepository.isolateName);
    }

    IsolateNameServer.registerPortWithName(
        port.sendPort, LocationServiceRepository.isolateName);

    port.listen(
      (dynamic data) async {
        await updateUI(data);
      },
    );
    initPlatformState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> updateUI(LocationDto data) async {
    final log = await FileManager.readLogFile();
    setState(() {
      if (data != null) {
        lastLocation = data;
        lastTimeLocation = DateTime.now();
      }
      logStr = log;
    });
  }

  Future<void> initPlatformState() async {
    print('Initializing...');
    await BackgroundLocator.initialize();
    logStr = await FileManager.readLogFile();
    print('Initialization done');
    final _isRunning = await BackgroundLocator.isRegisterLocationUpdate();
    setState(() {
      isRunning = _isRunning;
    });
    print('Running ${isRunning.toString()}');
  }

  @override
  Widget build(BuildContext context) {
    final start = SizedBox(
      width: double.maxFinite,
      child: RaisedButton(
        child: Text('Start'),
        onPressed: () {
          _onStart();
        },
      ),
    );
    final stop = SizedBox(
      width: double.maxFinite,
      child: RaisedButton(
        child: Text('Stop'),
        onPressed: () {
          onStop();
        },
      ),
    );
    final clear = SizedBox(
      width: double.maxFinite,
      child: RaisedButton(
        child: Text('Clear Log'),
        onPressed: () {
          FileManager.clearLogFile();
          setState(() {
            logStr = '';
          });
        },
      ),
    );
    String msgStatus = "-";
    if (isRunning != null) {
      if (isRunning) {
        msgStatus = 'Is running';
      } else {
        msgStatus = 'Is not running';
      }
    }
    final status = Text("Status: $msgStatus");

    String lastRunTxt = "-";
    if (isRunning != null) {
      if (isRunning) {
        if (lastTimeLocation == null || lastLocation == null) {
          lastRunTxt = "?";
        } else {
          lastRunTxt =
              LocationServiceRepository.formatDateLog(lastTimeLocation) +
                  "-" +
                  LocationServiceRepository.formatLog(lastLocation);
        }
      }
    }
    final lastRun = Text(
      "Last run: $lastRunTxt",
    );

    final log = Text(
      logStr,
    );

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter background Locator'),
        ),
        body: Container(
          width: double.maxFinite,
          padding: const EdgeInsets.all(22),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[start, stop, clear, status, lastRun, log],
            ),
          ),
        ),
      ),
    );
  }

  void onStop() {
    BackgroundLocator.unRegisterLocationUpdate();
    setState(() {
      isRunning = false;
//      lastTimeLocation = null;
//      lastLocation = null;
    });
  }

  void _onStart() async {
    if (await _checkLocationPermission()) {
      _startLocator();
      setState(() {
        isRunning = true;
        lastTimeLocation = null;
        lastLocation = null;
      });
    } else {
      // show error
    }
  }

  Future<bool> _checkLocationPermission() async {
    final access = await LocationPermissions().checkPermissionStatus();
    switch (access) {
      case PermissionStatus.unknown:
      case PermissionStatus.denied:
      case PermissionStatus.restricted:
        final permission = await LocationPermissions().requestPermissions(
          permissionLevel: LocationPermissionLevel.locationAlways,
        );
        if (permission == PermissionStatus.granted) {
          return true;
        } else {
          return false;
        }
        break;
      case PermissionStatus.granted:
        return true;
        break;
      default:
        return false;
        break;
    }
  }

  void _startLocator() {
    Map<String, dynamic> data = {'countInit': 1};
    BackgroundLocator.registerLocationUpdate(
      LocationCallbackHandler.callback,
      initCallback: LocationCallbackHandler.initCallback,
      initDataCallback: data,
/*
        Comment initDataCallback, so service not set init variable,
        variable stay with value of last run after unRegisterLocationUpdate
 */
      disposeCallback: LocationCallbackHandler.disposeCallback,
      androidNotificationCallback: LocationCallbackHandler.notificationCallback,
      settings: LocationSettings(
          notificationChannelName: "Location tracking service",
          notificationTitle: "Start Location Tracking example",
          notificationMsg: "Track location in background example",
          wakeLockTime: 20,
          autoStop: false,
          distanceFilter: 10,
          interval: 5),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  background_locator: ^1.1.10+1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:background_locator/background_locator.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
90
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
95
Learn more about scoring.

We analyzed this package on Jul 2, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform linux

Because of import path [package:background_locator/background_locator.dart] that declares support for platforms: android, ios

Package does not support Flutter platform macos

Because of import path [package:background_locator/background_locator.dart] that declares support for platforms: android, ios

Package does not support Flutter platform web

Because of import path [package:background_locator/background_locator.dart] that declares support for platforms: android, ios

Package does not support Flutter platform windows

Because of import path [package:background_locator/background_locator.dart] that declares support for platforms: android, ios

Package not compatible with SDK dart

because of import path [background_locator] that is in a package requiring null.

Health suggestions

Fix lib/background_locator.dart. (-0.50 points)

Analysis of lib/background_locator.dart reported 1 hint:

line 15 col 30: The value of the field '_background' isn't used.

Format lib/generated/i18n.dart.

Run flutter format to format lib/generated/i18n.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8
Dev dependencies
flutter_test