Giter Site home page Giter Site logo

kibotu / geofencer Goto Github PK

View Code? Open in Web Editor NEW
126.0 16.0 28.0 949 KB

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

License: MIT License

Kotlin 94.20% Java 5.80%
android geofencing kotlin background boot hacktoberfest android-library kotlin-android kotlin-library hacktoberfest2023

geofencer's Introduction

Geofencer

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

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

Features

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

sample.gif

Requirements

  1. Location permissions in AndroidManifest.xml

     <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" />
    
  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 NotificationWorker : GeoFenceUpdateModule() {
	
    override fun onGeofence(geofence: Geofence) {
    	Timber.v(, "onGeofence $geofence")
    }
}
  1. 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).addGeofenceWorker(geofence, NotificationWorker::class.java) { /* successfully added geofence */ }

Location Tracker

TODO: replace with worker

  1. Create Receiver
class LocationTrackerWorker : LocationTrackerUpdateModule() {

	override fun onLocationResult(locationResult: LocationResult) {  
		Log.v(GeoFenceIntentService::class.java.simpleName, "onLocationResult $location")
  }
}
  1. Start tracking
LocationTracker.requestLocationUpdates(this, LocationTrackerWorker::class.java)
  1. Stop tracking
LocationTracker.removeLocationUpdates(requireContext())

How to use in Java

Geofence

  1. Create Receiver
public class NotificationWorker extends GeoFenceUpdateModule {
	
	@Override
	public void onGeofence(@NotNull Geofence geofence) {
    	Timber.d("onGeofence " + geofence);
   	}
}
  1. 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.addGeofenceWorker(geofence, NotificationWorker.class,
   	 () -> /* successfully added geofence */ Unit.INSTANCE);        	 

Location Tracker

  1. Create Receiver
public class LocationTrackerWorker extends LocationTrackerUpdateModule {

    @Override
    public void onLocationResult(@NotNull LocationResult location) {
	
        Log.v(GeoFenceIntentService.class.getSimpleName(), "onLocationResult " + location);		        );
    }
}
  1. Start tracking
LocationTracker.INSTANCE.requestLocationUpdates(this, LocationTrackerWorker.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)

Mohammed Khalid Hamid

geofencer's People

Contributors

agnaldonp avatar en-jschuetze avatar khalid64927 avatar kibotu avatar sprotte avatar vidyajejurkar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

geofencer's Issues

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

In Android 12, 13, 14 Background Location not working

@kibotu @khalid64927

In android 12, 13, 14 background locations not working not even foreground, Already ask permission in my code I also ask background permission and send user in setting screen to click on "Allow all the time", with all this things still library not getting background location not even foreground, please look in to it.

Thanks

news

@kibotu I was looking to contribute something and got the geofencer. I would be happy to share technical knowledge to help with new features

If you want and find it interesting

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.

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

not enough information to infer type variable T

I don't know kotlin and can't solve this myself, the following line:
Geofencer(this).addGeofence(geofence, GeoFenceIntentService::class.java) { }

is complaining with the following message:
not enough information to infer type variable T

Move to non-exozet Organization

Hallo @kibotu,

can you move the project to another organization? Or a public repo of yours? I changed the LICENSE accordingly at cfb8023.

We are in the process of archiving the exozet organization.

Best regards

Jan

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

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

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

[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());
}
}

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

Cannot resolve symbol 'LocationTrackerUpdateModule'

I am working on including Geolocator in my JAVA based Android Studio project.

I have added below in my build.gradle file inside dependencies section --
implementation 'com.sprotte:Geolocator:latest'

Next, in my MainActivity.java class I extend the LocationTrackerWorker as specified in the readme file --

`
public class LocationTrackerWorker extends LocationTrackerUpdateModule {

    @Override
    public void onLocationResult(@NotNull LocationResult location) {

        Log.v(GeoFenceIntentService.class.getSimpleName(), "onLocationResult " + location);
        );
    }
}

`

However the class LocationTrackerUpdateModule does not get resolved.
I tried manually adding import com.sprotte.geolocator.tracking.LocationTracker; at the top of my Activity. That also gives the error Cannot resolve symbol 'sprotte'.

Kindly advice.

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);

Using this library in Java

I am working on a flutter project where i want to update data in background as there is not much solution available i have to use some native code as but i am a java developer and half of my project will be in java ,flutter and swift hope you may help me in setting this.

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.

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.