Location tracking & geofencing the easy way. Supports background, killed app, rebooted device different update intervals.

Overview

Geofencer

Build Status Download Hits-of-Code API Gradle Version Kotlin Android Arsenal

Convience library to receive user location updates and geofence events with minimal effort.

Features:

  • supports Android-Q
  • receive updates on background
  • receive updates if app got killed
  • geofence updates (dwell, enter, exit)
  • location updates
  • configurable update intervals

sample.gif

Requirmenets

  1. Location permissions in AndroidManifest.xml

     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
  2. Google maps api key

     <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY</string>
    

How to use

Geofence

  1. Create Receiver
class GeofenceIntentService : GeofenceIntentService() {
	
    override fun onGeofence(geofence: Geofence) {
    	Log.v(GeoFenceIntentService::class.java.simpleName, "onGeofence $geofence")	    
    }
}
  1. Add receiver to your manifest

     <service
         android:name=".kotlin.GeoFenceIntentService"
         android:permission="android.permission.BIND_JOB_SERVICE" />
    
  2. Start geofence tracking

val geofence = Geofence(
    id = UUID.randomUUID().toString(),
    latitude = 51.0899232,
    longitude = 5.968358,
    radius = 30.0,
    title = "Germany",
    message = "Entered Germany",
    transitionType = GEOFENCE_TRANSITION_ENTER
)
    
Geofencer(this).addGeofence(geofence, GeoFenceIntentService::class.java) { /* successfully added geofence */ }

Location Tracker

  1. Create Receiver
class LocationTrackerService : LocationTrackerUpdateIntentService() {

	override fun onLocationResult(locationResult: LocationResult) {  
		Log.v(GeoFenceIntentService::class.java.simpleName, "onLocationResult $location")
  }
}
  1. Add receiver to manifest

     <service
         android:name=".kotlin.LocationTrackerService"
         android:permission="android.permission.BIND_JOB_SERVICE" />
    
  2. Start tracking

LocationTracker.requestLocationUpdates(this, LocationTrackerService::class.java)
  1. Stop tracking
LocationTracker.removeLocationUpdates(requireContext())

How to use in Java

Geofence

  1. Create Receiver
public class GeoFenceIntentService extends GeofenceIntentService {
	
	@Override
	public void onGeofence(@NotNull Geofence geofence) {
	
    	Log.v(GeoFenceIntentService.class.getSimpleName(), "onGeofence " + geofence);	    	
   	}
}
  1. Add receiver to your manifest

     <service
         android:name=".java.GeoFenceIntentService"
         android:permission="android.permission.BIND_JOB_SERVICE" />
    
  2. Start geofence tracking

Geofence geofence = new Geofence(
        UUID.randomUUID().toString(),
        51.0899232,
        5.968358,
        30.0,
        "Germany",
        "Entered Germany",
        GEOFENCE_TRANSITION_ENTER);
Geofencer geofencer = new Geofencer(this);
geofencer.addGeofence(geofence, GeoFenceIntentService.class,
   	 () -> /* successfully added geofence */ Unit.INSTANCE);        	 

Location Tracker

  1. Create Receiver
public class LocationTrackerService extends LocationTrackerUpdateIntentService {

    @Override
    public void onLocationResult(@NotNull LocationResult location) {
	
        Log.v(GeoFenceIntentService.class.getSimpleName(), "onLocationResult " + location);		        );
    }
}
  1. Add receiver to manifest

     <service
         android:name=".java.LocationTrackerService"
         android:permission="android.permission.BIND_JOB_SERVICE" />
    
  2. Start tracking

LocationTracker.INSTANCE.requestLocationUpdates(this, LocationTrackerService.class);
  1. Stop tracking
LocationTracker.INSTANCE.removeLocationUpdates(this);

How to install

jCenter / mavenCentral

implementation 'com.sprotte:Geolocator:latest'

or Jiptack

Step 1. Add the JitPack repository to your build file

Add it in your root build.gradle at the end of repositories:

allprojects {
	repositories {
		maven { url 'https://jitpack.io' }
	}
}
Step 2. Add the dependency
dependencies {
	implementation 'com.github.exozet:Geolocator:latest'
	implementation 'com.google.android.gms:play-services-location:17.0.0'
}

Configuration

Default Location tracking update intervals can be overriden, by adding following parameter into your app/res/ - folder, e.g. app/res/config.xml

    <!-- Location Tracker -->
    <integer name="location_update_interval_in_millis">0</integer>
    <integer name="location_fastest_update_interval_in_millis">0</integer>
    <integer name="location_max_wait_time_interval_in_millis">0</integer>
    <integer name="location_min_distance_for_updates_in_meters">0</integer>

    <!-- Geofencer -->
    <integer name="loitering_delay">1</integer>
    <integer name="notification_responsiveness">1</integer>
    <integer name="expiration_duration">-1</integer> // -1 == NEVER_EXPIRE

You can also set this values at runtime in some step before call method requestLocationUpdates

    int interval = 1000;
    int fastestInterval = 2000;
    int priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
    int maxWaitTime = 10000;
    int smallestDisplacement = 20;

    LocationTrackerParams locationTrackerParams = new LocationTrackerParams(
            interval, fastestInterval, priority, maxWaitTime, smallestDisplacement);

    LocationTracker.INSTANCE.requestLocationUpdates(this, LocationTrackerService.class, locationTrackerParams);

LocationTrackerParams is a open class for kotlin or a not final class for java, so if you don't need to setup all params you can extend it.

Known Issues

  • does not work when in doze mode #2

Contributors

Jan Rabe

Paul Sprotte

[AgnaldoNP] (https://github.com/AgnaldoNP)

Comments
  • Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.

    Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.

    Hello @kibotu

    In new android 12 version this error is occur dew to pending intent message log show this

    java.lang.IllegalArgumentException: : Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles. at android.app.PendingIntent.checkFlags(PendingIntent.java:382) at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:673) at android.app.PendingIntent.getBroadcast(PendingIntent.java:660) at com.sprotte.geolocator.tracking.LocationTracker.getTrackingPendingIntent(LocationTracker.kt:32) at com.sprotte.geolocator.tracking.LocationTracker.requestLocationUpdates(LocationTracker.kt:93) at com.sprotte.geolocator.tracking.LocationTracker.requestLocationUpdates(LocationTracker.kt:68) at com.royalways.montecarloretail.activity.LoginActivity$3.onResponse(LoginActivity.java:314) at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$retrofit2-DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89) at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$$ExternalSyntheticLambda1.run(Unknown Source:6) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8663) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

        my some R&D show this code 
        
         val updatedPendingIntent = PendingIntent.getActivity(
        applicationContext,
        NOTIFICATION_REQUEST_CODE,
        updatedIntent,
        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT // setting the mutability flag 
        )
    

    Since you are using AlarmManager you should be able to use the IMMUTABLE flag.

    Please look in to it.

    thanks

    help wanted 
    opened by rajam1215 7
  • Difficult to get Lat Long and Address

    Difficult to get Lat Long and Address

    Hello @kibotu

    Library is very accurate but the Lat Long and Address not coming properly from Library. library give location update with that manner

    E/LocationTrackerService: onLocationResult [Location[fused 37.422065,-122.084084 hAcc=603 et=+2h8m29s292ms vAcc=??? sAcc=??? bAcc=???]]

    Please make some methods in lib to fetch lat, long and address with functions (methods)

    for example getLat(); getLong; getAddress();

    Thanks

    opened by rajam1215 5
  • Doesnt work if the device is in Doze Model

    Doesnt work if the device is in Doze Model

    There is an issue with any geofence library that it doesn't work when the device is in doze mode. If the device is in the car and person is going to office from home, then because of the doze mode state, geofence doesn't trigger. You can also try that use case, by forcing your phone into doze mode using adb commands.

    opened by mudassirzulfiqar 3
  • changing update frequency at runtime

    changing update frequency at runtime

    Hi Is it possible to supply the values that determines how long before we get a location update at runtime instead of using config.xml ? I am trying to allow the users to specify these parameters , so it's not convenient to have them hard-coded in an xml file

    Thank you

    enhancement help wanted 
    opened by IsslamEl 2
  • LOCATION ACCURACY

    LOCATION ACCURACY

    How to you configure for use of GPS and other Location strategies such as

    criteria.setPowerRequirement(Criteria.POWER_LOW); // Chose your desired power consumption level. criteria.setAccuracy(Criteria.ACCURACY_FINE);

    enhancement help wanted 
    opened by Kreateyou 2
  • [Question] Multiple transition types

    [Question] Multiple transition types

    Is it possible to use multiple transition types? like:

    
    return new Geofence(
                    String.valueOf(id),
                    latLng.latitude,
                    latLng.longitude,
                    radius,
                    name,
                    name,
                    GEOFENCE_TRANSITION_ENTER | GEOFENCE_TRANSITION_DWELL | GEOFENCE_TRANSITION_EXIT);
    

    And then check the transition type on the service:

     private void handleEnterExit(Geofence geofence) {
                int transitionType = geofence.getTransitionType();
            
                if (GEOFENCE_TRANSITION_ENTER == transitionType || GEOFENCE_TRANSITION_DWELL == transitionType) {
    Log.d(TAG, "Triggered enteringa geofence location: " + locationFound.getName());
    }
    }
    
    enhancement help wanted 
    opened by galadril 2
  • when i am try to add dependency i am getting this error

    when i am try to add dependency i am getting this error

    Failed to resolve: com.sprotte:Geolocator:1.4.0 Show in Project Structure dialog Affected Modules: app

    same error we are getting in this dependency implementation 'com.github.exozet:Geolocator:latest'

    opened by ashish07akg 1
  • location_min_distance_for_updates_in_meters not working as intended

    location_min_distance_for_updates_in_meters not working as intended

    Hi I have changed the xml values as follow: `

    <integer name="location_update_interval_in_millis">180000</integer>
    <integer name="location_fastest_update_interval_in_millis">180000</integer>
    <integer name="location_max_wait_time_interval_in_millis">300000</integer>
    <integer name="location_min_distance_for_updates_in_meters">50</integer>
    
    I get a log entry every 3 minutes which is correct. But when the current location changes significantly, it should fire again but I get nothing. I'm using [this app](https://play.google.com/store/apps/details?id=com.blogspot.newapphorizons.fakegps) to fake my location on the emulator and I move my location few km away but the event keeps waiting for that time interval. It should work on both time interval and min_distance settings, right?

    EDIT: I've noticed that the first three integer values are used here: https://github.com/exozet/Geolocator/blob/master/Geolocator/src/main/java/com/sprotte/geolocator/tracking/LocationTracker.kt but the location_min_distance_for_updates_in_meters is not used. Could this be it? How to solve it?

    Thanks very much

    bug 
    opened by IsslamEl 1
  • Using on Wear OS devices

    Using on Wear OS devices

    This is not an issue really, I am just wondering if this library can be used on Wear OS devices. I am trying to use the Geofence but I am not getting any hit. By the way how do you set the LoiteringDelay for delay between GEOFENCE_TRANSITION_ENTER and GEOFENCE_TRANSITION_DWELLING? I am running it on a Fossil Falster 3, Android 9, API 28.

    enhancement help wanted 
    opened by alborzs 1
  • [Feature] Set Expiration and Lointering delay on Geofence

    [Feature] Set Expiration and Lointering delay on Geofence

    Would be cool to also set the expiration duration, and loitering delay on the Geofence object.

    For example:

    .setExpirationDuration(Geofence.NEVER_EXPIRE)
    .setLoiteringDelay(3000)
    
    enhancement help wanted 
    opened by galadril 1
  • Need to do for Auto start permission for some mobile brands or chines brands

    Need to do for Auto start permission for some mobile brands or chines brands

    Hello @kibotu

    Need to do auto start permission for these kind of devices, I r&d on that, please do this stuff in your library, with this thing you can solve this issue and made this awesome.

    please take help from this library. it will help you how to start auto permission. https://github.com/judemanutd/AutoStarter

    It works fine in reputed companies phone brand like Google, Samsung etc, but it is have some restriction with chines brands like OPPO, VIVO, MI.

    Screenshot Capture - 2019-10-16 - 11-18-51 Screenshot Capture - 2019-10-16 - 11-19-06 Screenshot Capture - 2019-10-16 - 11-18-30

    This example for MI phones but there are some other brands are here, please check the given link.

    https://github.com/judemanutd/AutoStarter

    Thanks

    help wanted 
    opened by rajam1215 1
  • In Android 12 Background Location not working

    In Android 12 Background Location not working

    @kibotu

    Hello

    In android background location not working, I am didn't get any location after the version 31 (Android 12) on higher version form android 12 location service not working. please look in to it.

    Thanks Bishal Malick

    opened by rajam1215 0
  • I am not able to get callback when i am enter or exit in geo fence location

    I am not able to get callback when i am enter or exit in geo fence location

    I am not able to get callback when i am enter or exit in geo fence location class GeofenceIntentService : GeofenceIntentService() {

    override fun onGeofence(geofence: Geofence) {
    	Log.v(GeoFenceIntentService::class.java.simpleName, "onGeofence $geofence")	    
    }
    

    }

    this method not called . so please help

    opened by ashish07akg 0
  • Please specify that android 10 or up devices need ACCESS_BACKGROUND_LOCATION

    Please specify that android 10 or up devices need ACCESS_BACKGROUND_LOCATION

    Permission needed :- ACCESS_BACKGROUND_LOCATION

    if we don't add this permission ACCESS_BACKGROUND_LOCATION in manifest & don't take permission from user at runtime then lib. is not able to add geo-fence


    see this stackoverflow answer.


    so please update the lib for this and mention the permission that user need to declare this in manifest.

    opened by PratikPsb99 0
Owner
null
An easy, flexible way to add a shimmering effect to any view in an Android app.

Shimmer for Android Shimmer is an Android library that provides an easy way to add a shimmer effect to any view in your Android app. It is useful as a

Facebook 5.1k Dec 26, 2022
[] Easily have blurred and transparent background effect on your Android views.

##[DEPRECATED] BlurBehind Easily have blurred and transparent background effect on your Android views. Before API level 14 there was a Window flag cal

Gokberk Ergun 516 Nov 25, 2022
User onboarding library with smooth animation of objects and background colors

SlidingTutorial Cleveroad introduces Sliding Tutorial Library for Flutter Hey guys, hope you haven’t started developing a tutorial for your Flutter ap

Cleveroad 127 Dec 31, 2022
:sparkles: An easy way to implement an elastic touch effect for Android.

ElasticViews ✨ An easy way to implement an elastic touch effect for Android. Including in your project Gradle Add below codes to your root build.gradl

Jaewoong Eum 763 Dec 29, 2022
Library provides an easy way to a add shimmer effect in Android Compose project.

Add a shimmer effect to the layout in Android Compose

Valery 66 Dec 14, 2022
Awesome keyboard animator that supports Android SDK 23 ✨

KeyboardBeautify Awesome keyboard animator that supports Android SDK 23 ✨ This library was created based on the android/user-interface-samples. Previe

Ji Sungbin 9 Dec 8, 2022
🌠 Transform into a different view or activity using morphing animations.

TransformationLayout ?? Transform into a different view or activity using morphing animations. Using Transformation motions of new material version. D

Jaewoong Eum 2k Jan 3, 2023
Thirty-one different easing animation interpolators for Android.

EasingInterpolator Thirty-one different easing animation interpolators for Android. It does not use the standard 4 param ease signature. Instead it us

Masayuki Suda 1.1k Dec 28, 2022
A sample implementation Compose BottomSheet with animation different states

Compose Animated BottomSheet A sample implementation Compose BottomSheet with animation different states Medium post: https://proandroiddev.com/how-to

Yahor 40 Jan 6, 2023
Combine ViewPager and Animations to provide a simple way to create applications' guide pages.

WoWoViewPager WoWoViewPager combines ViewPager and Animations to provide a simple way to create applications' guide pages. When users are dragging WoW

Nightonke 2.7k Dec 30, 2022
Android library to control Transition animates. A simple way to create a interactive animation.

TransitionPlayer Android library to control Transition animates. A simple way to create a interactive animation. Demo1 SimpleTransition Code: ....

ζž—ζ³•ι‘« 1.2k Dec 17, 2022
Simple way to animate your views on Android with Rx πŸš€

This is an Android library to make a simple way to animate your views on Android with Rx.

Lopez Mikhael 583 Dec 9, 2022
Android library to control Transition animates. A simple way to create a interactive animation.

TransitionPlayer Android library to control Transition animates. A simple way to create a interactive animation. Demo1 SimpleTransition Code: ....

ζž—ζ³•ι‘« 1.2k Dec 17, 2022
Chandrasekar Kuppusamy 799 Nov 14, 2022
Introduction your app to the user , Easy to use and set Items as you want

Introduction App This lib helps to introduce the App-by view page based on Kotlin. Features Easy Set up Items: Title, Describe, Background, Buttons Ap

S.M.Zendehbad 0 May 6, 2022
Allows the easy creation of animated transition effects when the state of Android UI has changed

android-transition Android-Transition allows the easy creation of view transitions that reacts to user inputs. The library is designed to be general e

Kai 615 Nov 14, 2022
A Photo Editor library with simple, easy support for image editing using paints,text,filters,emoji and Sticker like stories.

PhotoEditor A Photo Editor library with simple, easy support for image editing using Paints, Text, Filters, Emoji and Sticker like stories. Features D

Burhanuddin Rashid 3.6k Jan 9, 2023
πŸ’³ A quick and easy flip view through which you can create views with two sides like credit cards, poker cards etc.

The article on how this library was created is now published. You can read it on this link here. β†’. ?? EasyFlipView Built with ❀︎ by Wajahat Karim and

Wajahat Karim 1.3k Dec 14, 2022
FPSAnimator is very easy animation library for Android TextureView and SurfaceView.

FPSAnimator A simple but powerful Tween / SpriteSheet / ParabolicMotion / animation library for Android TextureView and SurfaceView. Features The cont

Masayuki Suda 756 Dec 30, 2022