Skip to content

Commit

Permalink
Merge pull request #9 from icapps/bugfix/#8-missing-plugins-in-backgr…
Browse files Browse the repository at this point in the history
…ound

#8 Fixed the issue where the plugins were not yet registered
  • Loading branch information
vanlooverenkoen authored Dec 24, 2020
2 parents 1b659f8 + bb66e77 commit 52990db
Show file tree
Hide file tree
Showing 9 changed files with 189 additions and 13 deletions.
82 changes: 81 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,84 @@
A new Flutter plugin that allows you to track the background location for Android & iOS

[![Build Status](https://travis-ci.com/icapps/flutter-background-location-tracker.svg?branch=master)](https://travis-ci.com/icapps/flutter-background-location-tracker)
[![Coverage Status](https://coveralls.io/repos/github/icapps/flutter-background-location-tracker/badge.svg?branch=master)](https://coveralls.io/github/icapps/flutter-background-location-tracker?branch=master)
[![Coverage Status](https://coveralls.io/repos/github/icapps/flutter-background-location-tracker/badge.svg?branch=master)](https://coveralls.io/github/icapps/flutter-background-location-tracker?branch=master)

## Android Config

### Update compile sdk

Compile sdk should be at 29 at least.
```
android {
...
compileSdkVersion 29
...
defaultConfig {
...
targetSdkVersion 29
...
}
...
}
```

## iOS Configuration

### Update Info.plist

Add the correct permission descriptions
```
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Your description why you should use NSLocationAlwaysAndWhenInUseUsageDescription</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Your description why you should use NSLocationAlwaysAndWhenInUseUsageDescription</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Your description why you should use NSLocationAlwaysAndWhenInUseUsageDescription</string>
```

Add the background location updates in xcode

Or add the info to the Info.plist

```
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
```

### Update the AppDelegate

Make sure you call the `setPluginRegistrantCallback` so other plugins can be accessed in the background.

```
import UIKit
import Flutter
import background_location_tracker
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
GeneratedPluginRegistrant.register(with: self)
BackgroundLocationTrackerPlugin.setPluginRegistrantCallback { registry in
GeneratedPluginRegistrant.register(with: registry)
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
```


FAQ:

#### I get a Unhandled Exception: MissingPluginException(No implementation found for method .... on channel ...)

```
This is mostly caused by a misconfiguration of the plugin:
Android Pre v2 embedding: make sure the plugin registrant callback is set
Android v2 embedding: Log a new github issues. This
iOS: make sure the plugin registrant callback is set
```
8 changes: 7 additions & 1 deletion example/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,33 @@ PODS:
- background_location_tracker (0.0.1):
- Flutter
- Flutter (1.0.0)
- flutter_local_notifications (0.0.1):
- Flutter
- "permission_handler (5.0.1+1)":
- Flutter

DEPENDENCIES:
- background_location_tracker (from `.symlinks/plugins/background_location_tracker/ios`)
- Flutter (from `Flutter`)
- flutter_local_notifications (from `.symlinks/plugins/flutter_local_notifications/ios`)
- permission_handler (from `.symlinks/plugins/permission_handler/ios`)

EXTERNAL SOURCES:
background_location_tracker:
:path: ".symlinks/plugins/background_location_tracker/ios"
Flutter:
:path: Flutter
flutter_local_notifications:
:path: ".symlinks/plugins/flutter_local_notifications/ios"
permission_handler:
:path: ".symlinks/plugins/permission_handler/ios"

SPEC CHECKSUMS:
background_location_tracker: 3f0954d5a839b9bfffbdc887e679d183a7bbc1c9
Flutter: 0e3d915762c693b495b44d77113d4970485de6ec
flutter_local_notifications: 0c0b1ae97e741e1521e4c1629a459d04b9aec743
permission_handler: eac8e15b4a1a3fba55b761d19f3f4e6b005d15b6

PODFILE CHECKSUM: aafe91acc616949ddb318b77800a7f51bffa2a4c

COCOAPODS: 1.9.1
COCOAPODS: 1.10.0
11 changes: 10 additions & 1 deletion example/ios/Runner/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import UIKit
import Flutter
import background_location_tracker

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
GeneratedPluginRegistrant.register(with: self)


if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
}

BackgroundLocationTrackerPlugin.setPluginRegistrantCallback { registry in
GeneratedPluginRegistrant.register(with: registry)
}

return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
53 changes: 50 additions & 3 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:background_location_tracker/background_location_tracker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';

void _backgroundCallback() => BackgroundLocationTrackerManager.handleBackgroundUpdated((data) => Repo().update(data));
void _backgroundCallback() => BackgroundLocationTrackerManager.handleBackgroundUpdated((data) async => Repo().update(data));

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
Expand All @@ -13,7 +16,6 @@ Future<void> main() async {
config: const BackgroundLocationTrackerConfig(
androidConfig: AndroidConfig(
notificationIcon: 'explore',
enableCancelTrackingAction: false,
),
),
);
Expand Down Expand Up @@ -50,6 +52,15 @@ class _MyAppState extends State<MyApp> {
child: const Text('Request location permission'),
onPressed: _requestLocationPermission,
),
if (Platform.isIOS)
MaterialButton(
child: const Text('Request Notification permission'),
onPressed: _requestNotificationPermission,
),
MaterialButton(
child: const Text('Send notification'),
onPressed: () => sendNotification('Hallokes'),
),
if (isTracking != null) ...[
MaterialButton(
child: const Text('Start Tracking'),
Expand Down Expand Up @@ -90,6 +101,15 @@ class _MyAppState extends State<MyApp> {
print('NOT GRANTED'); // ignore: avoid_print
}
}

Future<void> _requestNotificationPermission() async {
final result = await Permission.notification.request();
if (result == PermissionStatus.granted) {
print('GRANTED'); // ignore: avoid_print
} else {
print('NOT GRANTED'); // ignore: avoid_print
}
}
}

class Repo {
Expand All @@ -99,5 +119,32 @@ class Repo {

factory Repo() => _instance ??= Repo._();

void update(BackgroundLocationUpdateData data) => print('Location Update: Lat: ${data.lat} Lon: ${data.lon}'); // ignore: avoid_print
void update(BackgroundLocationUpdateData data) {
final text = 'Location Update: Lat: ${data.lat} Lon: ${data.lon}';
print(text); // ignore: avoid_print
sendNotification(text);
}
}

void sendNotification(String text) {
const settings = InitializationSettings(
android: AndroidInitializationSettings('app_icon'),
iOS: IOSInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
),
);
FlutterLocalNotificationsPlugin().initialize(settings, onSelectNotification: (data) async {
print('ON CLICK $data'); // ignore: avoid_print
});
FlutterLocalNotificationsPlugin().show(
Random().nextInt(9999),
'Title',
text,
const NotificationDetails(
android: AndroidNotificationDetails('test_notification', 'Test', 'Test'),
iOS: IOSNotificationDetails(),
),
);
}
28 changes: 28 additions & 0 deletions example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_local_notifications:
dependency: "direct main"
description:
name: flutter_local_notifications
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.2"
flutter_local_notifications_platform_interface:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.0+1"
flutter_test:
dependency: "direct dev"
description: flutter
Expand Down Expand Up @@ -102,6 +116,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.1"
platform:
dependency: transitive
description:
name: platform
url: "https://pub.dartlang.org"
source: hosted
version: "2.2.1"
plugin_platform_interface:
dependency: transitive
description:
Expand Down Expand Up @@ -156,6 +177,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "0.2.19-nullsafety.2"
timezone:
dependency: transitive
description:
name: timezone
url: "https://pub.dartlang.org"
source: hosted
version: "0.5.9"
typed_data:
dependency: transitive
description:
Expand Down
1 change: 1 addition & 0 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ dependencies:
background_location_tracker:
path: ../
permission_handler: ^5.0.1+1
flutter_local_notifications: ^3.0.2

dev_dependencies:
flutter_test:
Expand Down
6 changes: 6 additions & 0 deletions ios/Classes/BackgroundLocationTrackerPlugin.m
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@
#endif

@implementation BackgroundLocationTrackerPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
[SwiftBackgroundLocationTrackerPlugin registerWithRegistrar:registrar];
}

+ (void)setPluginRegistrantCallback:(FlutterPluginRegistrantCallback)callback {
[SwiftBackgroundLocationTrackerPlugin setPluginRegistrantCallback:callback];
}

@end
3 changes: 1 addition & 2 deletions lib/src/background_location_tracker_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import 'package:background_location_tracker/src/model/background_location_update
import 'package:background_location_tracker/src/model/config/background_location_tracker_config.dart';
import 'package:background_location_tracker/src/util/logger.dart';

typedef LocationUpdateCallback = void Function(BackgroundLocationUpdateData data);
typedef LocationUpdateCallback = Future<void> Function(BackgroundLocationUpdateData data);

class BackgroundLocationTrackerManager {

static Future<void> initialize(Function callback, {BackgroundLocationTrackerConfig config}) {
final pluginConfig = config ??= const BackgroundLocationTrackerConfig();
BackgroundLocationTrackerLogger.enableLogging = pluginConfig.loggingEnabled;
Expand Down
10 changes: 5 additions & 5 deletions lib/src/channel/background_channel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,24 @@ class BackgroundChannel {
..setMethodCallHandler((call) async {
switch (call.method) {
case 'onLocationUpdate':
await handleLocationUpdate(call, callback, enableLogging: enableLogging);
break;
return handleLocationUpdate(call, callback, enableLogging: enableLogging);
default:
break;
return false;
}
})
..invokeMethod<void>(
'initialized',
);
}

static Future<void> handleLocationUpdate(MethodCall call, LocationUpdateCallback callback, {bool enableLogging = false}) async {
static Future<bool> handleLocationUpdate(MethodCall call, LocationUpdateCallback callback, {bool enableLogging = false}) async {
final data = call.arguments as Map<dynamic, dynamic>; // ignore: avoid_as
final isLoggingEnabled = data['logging_enabled'] as bool; // ignore: avoid_as
BackgroundLocationTrackerLogger.enableLogging = isLoggingEnabled;
BackgroundLocationTrackerLogger.log('locationUpdate: ${call.arguments}');
final lat = data['lat'] as double; // ignore: avoid_as
final lon = data['lon'] as double; // ignore: avoid_as
callback(BackgroundLocationUpdateData(lat: lat, lon: lon));
await callback(BackgroundLocationUpdateData(lat: lat, lon: lon));
return true;
}
}

0 comments on commit 52990db

Please sign in to comment.