Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Geofencing plugin #89

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ geofencing:
Also request the correct permissions for geofencing:

```xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
```
Expand All @@ -42,7 +43,6 @@ class Application : FlutterApplication(), PluginRegistrantCallback {
}

override fun registerWith(registry: PluginRegistry) {
GeneratedPluginRegistrant.registerWith(registry);
}
}
```
Expand All @@ -59,7 +59,6 @@ public class Application extends FlutterApplication implements PluginRegistrantC

@Override
public void registerWith(PluginRegistry registry) {
GeneratedPluginRegistrant.registerWith(registry);
}
}
```
Expand Down Expand Up @@ -105,6 +104,36 @@ And request the correct permissions for geofencing:
</dict>
```

Add this line to `Runner-Briding-Header.h`

```h
#import <geofencing/GeofencingPlugin.h>
```

At the end add this line to `AppDelegate.swift`

```swift
GeofencingPlugin.setPluginRegistrantCallback { (registry) in GeneratedPluginRegistrant.register(with: registry) }
```

### Notes
Before register geofence request permissions for location and location always. You can use *permission_handler* package. Don't forget include this line in `Podfile`

```ruby
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = 'NO'
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
'PERMISSION_LOCATION=1',
]
end
end
end
```

### Need Help?

For help getting started with Flutter, view our online
Expand Down
6 changes: 3 additions & 3 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ group 'io.flutter.plugins.geofencing'
version '1.0-SNAPSHOT'

buildscript {
ext.kotlin_version = '1.5.30'
ext.kotlin_version = '1.6.10'

repositories {
google()
jcenter()
}

dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath 'com.android.tools.build:gradle:7.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
Expand Down Expand Up @@ -41,6 +41,6 @@ android {
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "com.google.android.gms:play-services-location:17.+"
}
2 changes: 1 addition & 1 deletion android/gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip
Original file line number Diff line number Diff line change
Expand Up @@ -257,11 +257,6 @@ class GeofencingPlugin : ActivityAware, FlutterPlugin, MethodCallHandler {
val args = call.arguments<ArrayList<*>>()
when(call.method) {
"GeofencingPlugin.initializeService" -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
mActivity?.requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION), 12312)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mActivity?.requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 12312)
}
initializeService(mContext!!, args)
result.success(true)
}
Expand Down
6 changes: 3 additions & 3 deletions example/android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
compileSdkVersion 28
compileSdkVersion 33

sourceSets {
main.java.srcDirs += 'src/main/kotlin'
Expand All @@ -40,7 +40,7 @@ android {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "io.flutter.plugins.geofencing_example"
minSdkVersion 16
targetSdkVersion 28
targetSdkVersion 31
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
Expand All @@ -60,7 +60,7 @@ flutter {
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
Expand Down
3 changes: 2 additions & 1 deletion example/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:launchMode="singleTop"
android:exported="true"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
Expand All @@ -34,7 +35,7 @@
<receiver android:name="io.flutter.plugins.geofencing.GeofencingBroadcastReceiver"
android:enabled="true" android:exported="true"/>
<receiver android:name="io.flutter.plugins.geofencing.GeofencingRebootBroadcastReceiver"
android:enabled="true">
android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
Expand Down
4 changes: 2 additions & 2 deletions example/android/build.gradle
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
buildscript {
ext.kotlin_version = '1.3.50'
ext.kotlin_version = '1.6.10'
repositories {
google()
jcenter()
}

dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath 'com.android.tools.build:gradle:7.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
Expand Down
2 changes: 1 addition & 1 deletion example/android/gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip
105 changes: 55 additions & 50 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'dart:ui';
import 'package:flutter/material.dart';

import 'package:geofencing/geofencing.dart';
import 'package:permission_handler/permission_handler.dart';

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

Expand All @@ -20,28 +21,30 @@ class MyApp extends StatefulWidget {
class _MyAppState extends State<MyApp> {
String geofenceState = 'N/A';
List<String> registeredGeofences = [];
double latitude = 37.419851;
double longitude = -122.078818;
double radius = 150.0;
double latitude = 50.00187;
double longitude = 36.23866;
double radius = 200.0;
ReceivePort port = ReceivePort();
final List<GeofenceEvent> triggers = <GeofenceEvent>[
GeofenceEvent.enter,
GeofenceEvent.dwell,
GeofenceEvent.exit
];
final AndroidGeofencingSettings androidSettings = AndroidGeofencingSettings(
initialTrigger: <GeofenceEvent>[
GeofenceEvent.enter,
GeofenceEvent.exit,
GeofenceEvent.dwell
],
loiteringDelay: 1000 * 60);
initialTrigger: <GeofenceEvent>[
GeofenceEvent.enter,
GeofenceEvent.exit,
],
loiteringDelay: 0,
notificationResponsiveness: 0,
);

@override
void initState() {
super.initState();
IsolateNameServer.registerPortWithName(
port.sendPort, 'geofencing_send_port');
port.sendPort,
'geofencing_send_port',
);
port.listen((dynamic data) {
print('Event: $data');
setState(() {
Expand All @@ -51,14 +54,44 @@ class _MyAppState extends State<MyApp> {
initPlatformState();
}

void registerGeofence() async {
final firstPermission = await Permission.locationWhenInUse.request();
final secondPermission = await Permission.locationAlways.request();
if (firstPermission.isGranted && secondPermission.isGranted) {
await GeofencingManager.registerGeofence(
GeofenceRegion(
'mtv',
latitude,
longitude,
radius,
triggers,
androidSettings,
),
callback,
);
final registeredIds = await GeofencingManager.getRegisteredGeofenceIds();
setState(() {
registeredGeofences = registeredIds;
});
}
}

void unregisteGeofence() async {
await GeofencingManager.removeGeofenceById('mtv');
final registeredIds = await GeofencingManager.getRegisteredGeofenceIds();
setState(() {
registeredGeofences = registeredIds;
});
}

@pragma('vm:entry-point')
static void callback(List<String> ids, Location l, GeofenceEvent e) async {
print('Fences: $ids Location $l Event: $e');
final SendPort send =
IsolateNameServer.lookupPortByName('geofencing_send_port');
IsolateNameServer.lookupPortByName('geofencing_send_port');
send?.send(e.toString());
}

// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
print('Initializing...');
await GeofencingManager.initialize();
Expand Down Expand Up @@ -90,44 +123,16 @@ class _MyAppState extends State<MyApp> {
children: <Widget>[
Text('Current state: $geofenceState'),
Center(
child: RaisedButton(
child: TextButton(
child: const Text('Register'),
onPressed: () {
if (latitude == null) {
setState(() => latitude = 0.0);
}
if (longitude == null) {
setState(() => longitude = 0.0);
}
if (radius == null) {
setState(() => radius = 0.0);
}
GeofencingManager.registerGeofence(
GeofenceRegion(
'mtv', latitude, longitude, radius, triggers,
androidSettings: androidSettings),
callback).then((_) {
GeofencingManager.getRegisteredGeofenceIds().then((value) {
setState(() {
registeredGeofences = value;
});
});
});
},
onPressed: registerGeofence,
),
),
Text('Registered Geofences: $registeredGeofences'),
Center(
child: RaisedButton(
child: TextButton(
child: const Text('Unregister'),
onPressed: () =>
GeofencingManager.removeGeofenceById('mtv').then((_) {
GeofencingManager.getRegisteredGeofenceIds().then((value){
setState(() {
registeredGeofences = value;
});
});
}),
onPressed: unregisteGeofence,
),
),
TextField(
Expand All @@ -136,29 +141,29 @@ class _MyAppState extends State<MyApp> {
),
keyboardType: TextInputType.number,
controller:
TextEditingController(text: latitude.toString()),
TextEditingController(text: latitude.toString()),
onChanged: (String s) {
latitude = double.tryParse(s);
},
),
TextField(
decoration:
const InputDecoration(hintText: 'Longitude'),
const InputDecoration(hintText: 'Longitude'),
keyboardType: TextInputType.number,
controller:
TextEditingController(text: longitude.toString()),
TextEditingController(text: longitude.toString()),
onChanged: (String s) {
longitude = double.tryParse(s);
}),
TextField(
decoration: const InputDecoration(hintText: 'Radius'),
keyboardType: TextInputType.number,
controller:
TextEditingController(text: radius.toString()),
TextEditingController(text: radius.toString()),
onChanged: (String s) {
radius = double.tryParse(s);
}),
]))),
);
}
}
}
1 change: 1 addition & 0 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
permission_handler: ^10.2.0

dev_dependencies:
flutter_test:
Expand Down
4 changes: 2 additions & 2 deletions ios/Classes/GeofencingPlugin.m
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ - (instancetype)init:(NSObject<FlutterPluginRegistrar> *)registrar {
_eventQueue = [[NSMutableArray alloc] init];
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager requestAlwaysAuthorization];
_locationManager.allowsBackgroundLocationUpdates = YES;
// [_locationManager requestAlwaysAuthorization];
// _locationManager.allowsBackgroundLocationUpdates = YES;

_headlessRunner = [[FlutterEngine alloc] initWithName:@"GeofencingIsolate" project:nil allowHeadlessExecution:YES];
_registrar = registrar;
Expand Down
5 changes: 3 additions & 2 deletions lib/src/callback_dispatcher.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import 'package:flutter/services.dart';
import 'package:geofencing/src/geofencing.dart';
import 'package:geofencing/src/location.dart';

@pragma('vm:entry-point')
void callbackDispatcher() {
const MethodChannel _backgroundChannel =
MethodChannel('plugins.flutter.io/geofencing_plugin_background');
WidgetsFlutterBinding.ensureInitialized();

_backgroundChannel.setMethodCallHandler((MethodCall call) async {
final List<dynamic> args = call.arguments;
final Function callback = PluginUtilities.getCallbackFromHandle(
final Function? callback = PluginUtilities.getCallbackFromHandle(
CallbackHandle.fromRawHandle(args[0]));
assert(callback != null);
final List<String> triggeringGeofences = args[1].cast<String>();
Expand All @@ -29,7 +30,7 @@ void callbackDispatcher() {
.forEach((dynamic e) => locationList.add(double.parse(e.toString())));
final Location triggeringLocation = locationFromList(locationList);
final GeofenceEvent event = intToGeofenceEvent(args[3]);
callback(triggeringGeofences, triggeringLocation, event);
callback?.call(triggeringGeofences, triggeringLocation, event);
});
_backgroundChannel.invokeMethod('GeofencingService.initialized');
}
Loading