Geofencing sample app is not working with mock location - android

greetings
I have a ICE Cream sandwitch phone with google play service.
Installed the Geofencedetection sample app from the following
http://developer.android.com/training/location/geofencing.html
I also installed a Mock Location application
Using this mock location i have set my location as new delhi (lat 28.66 long 77.21).
Now i registered the following geofences using the sample app
Geofence1
lat 11.94898
long 79.48475
radius 1000 meters
Geofence2
lat 77.00000
long 77.00000
radius 1000 meters
Now i again opened the mock location and set the
location as (within geofence 1) my home.
lat 11.94898
long 79.48475
I have checked the mock location with the Maps application.
It displays correctly. I enabled the Allow Mock Locations
in Developer options
But the sample Geofence application is not triggering any
notification. I checked the code. As per the code it should send
notification when the user enters the geofence.
I could not understand why it is not sending notification.
Will this work only on real network?
Please let me know if i am doing anything wrong?
Best Regards
jothi

I had a similar experience using the sample MockLocation app from
http://developer.android.com/training/location/location-testing.html
For example if my geofence is set at 5,100 and I use the mocklocation app to inject a single mock location at 5,100, the geofence will not trigger.
However, if you repeatedly inject multiple mock locations at 5,100 the geofence will trigger. In my case, injecting mock locations at 5,100 three times consecutively caused my geofence to trigger. To be clear, when I say inject I mean doing:
mLocationClient.setMockLocation(yourMockLocation);
Everything below is pure speculation on my part so take it with a grain of salt:
My speculation is there is some filtering algorithm in the LocationClient backend whose purpose is to filter out spurious sensor values and it might be detecting that huge change in lat/long as a possible spurious value. Another possibility is the geofence simply doesnt trigger until it receives multiple readings that indicate you are within its vicinity.

Please check notification of app when app in foreground because i am also not getting any update for geofence in background. But in foreground, It is working fine.

I have stuck with this problem for sometime. Then eventually it turns out the google mock location tutorial (http://developer.android.com/training/location/location-testing.html) failed to mention you will need to set below two calls with the mock location you created:
/*
setElapsedRealtimeNanos() was added in API 17
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
newLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
}
newLocation.setTime(System.currentTimeMillis());
Without these two calls my mock location won't trigger my geofence. After calling these my geofence is triggered without issues.

I also had a similar experience with MockLocation app, just use a large number of seconds on "send interval" field, like 7 seconds, and the geofence will trigger.

After spending a ton of time on this I finally figured out that the secret was to use the provider name "network" when creating the mock location instance.
Location location = new Location("network");

Related

Get Location Updates in Background Service - Android Studio

after researching the Android Location FusedLocationProviderClient I am very confused about what you should and should not do!
The use case is: The App holds different locations with latitude and longitude. While the user is walking around the app (with the phone in the pocket, screen off) needs to track if he is close to one of the locations and plays a short beep when closer than a defined range.
Would the Geofence option the best solution? These locations will also change during runtime and periodically - they might also be more than 100. Any suggestion?
I am also thinking about a background service to handle all this when the device moves. This would be more flexible and allows for the reload of the locations as well. Any thoughts?
Thanks!!
You don't actually need to build a background service to monitor if a user is close to a location. There is already a geofence provided by Google. It uses fusedlocation provider internally.
Please refer this
You can combine this with a FusedLocationProviderClient and subscribe to location updates. This way you'll get location updates as well.

Notify when user is in my location in Android

I am looking for an easy way to check if a user is at my location (50m) radius if notify me.
Right now I have a service running every two minutes getting position of each user comparing it and then notifying if user in same location.
Can this be done using promixityalert: http://goo.gl/9I857T?
Thanks!
Instead ProximityAlert I would use Geofences.
http://developer.android.com/training/location/geofencing.html
Is newer and does a more effective use of the battery
In your case, you can have a service that sends to the other device the current location every X minutes, so it can update the Geofence. The problem that I see is that there would be a lot of calls, spending battery and the data plan.
A good approach is to use the Location Services API, you can detect if a user is standing or moving.
http://developer.android.com/training/location/activity-recognition.html
Using this and sending new locations only when the user is moving you will be able to reduce the amount of calls.
Parse is another option as #thepace mention. It is easy to use and whit it would be easy to implement what you are trying to do, but is not free :(
Hope it helps.
Issue: Check if any user (multiple and variable location) is within specific radius of my current location(variable).
Solution:
1. Parse.com
a) Ensure every user has their location updated in Parse DB including yours.
https://parse.com/tutorials/anywall-android
b) Use push notificaitons: https://parse.com/docs/push_guide#setup/Android
1> Create a channel wherein only you are subscribed.
2> Create your installation query and send notification to it to the channel subscribed.

Geofencing in android app

I am building a check in and check out application currently. User should be able to check in with the current location and when he goes 50 meters away from the current location he should be checked out.
Can this be implemented using Geo Fencing for android?
I came across this piece of code but do not know how to use:
SimpleGeofence mUIGeofence1 = new SimpleGeofence("1",
Double.valueOf(mLatitude1.getText().toString()),
Double.valueOf(mLongitude1.getText().toString()),
Float.valueOf(mRadius1.getText().toString()),
GEOFENCE_EXPIRATION_TIME,
// This geofence records only entry transitions
Geofence.GEOFENCE_TRANSITION_ENTER);
mGeofenceStorage.setGeofence("1", mUIGeofence1);
I would really appreciate if the correct way to use geo fencing could be given.
You can implement this using geofencing.
The sample code you posted has to do with persisting a Geofence object.
If you want to know how to register a Geofence, check out this presentation on using the geofencing APIs and these android docs. The prezi has some sample code that boils down the use of the APIs to 10 lines of code.

Android Location Updates get stuck

I am developing an android application wherein I need the user location updates pretty frequently. Say 2 times a minute.
Earlier I had been using Google Play Service's "Fused location service" but the location updates were not received as requested.
The location updates got stuck for sometime, the interval between updates jumped to 10min or so.Sometimes even if I put my priority to "PRIORITY_HIGH_ACCURACY" the same happened.
I then went back to the old "Location Manager" and when I used the "NETWORK_PROVIDER", I noticed that the location updates got stuck due to this provider. Also the GPS does not get activated immediately, it takes some time. I am trying to build my custom fused location provider. How can I efficiently switch between providers, without getting lags on location updates.
I want to know what are the best practices for getting location updates regularly, all the time, be it either NW, GPS or both. Like it should work for an application where location updates getting stuck cannot be afforded.
Battery drain is not an issue for me right now.I am aware of all the supporting docs that Google provides regarding location access.
Any help would be much appreciated.
Thankyou !
FusedLocationProvider really is the best option for obtaining locations at the moment, because it uses a lot more than just GPS or Network data to obtain location fixes. I have experienced issues regarding intervals being missed as well, but ultimately this is something down to luck depending on availability of GPS, Network, etc. etc.
My favourite usage of FusedLocationProvider so far is in conjunction with the AlarmManager class: Basically, the idea is to start location tracking at intervals specified by the Alarm Manager (this can be set to every 30 seconds such as in your case). Once the interval is hit, the location provider is to obtain a location fix as soon as possible (so in the setInterval method or whatever it's called, the parameter is a 0). This way, you can avoid having to wait another 30 seconds for a new location, instead having the location tracker attempt to provide a location as soon as possible after the interval specified by the Alarm Manager is hit.
By the way, when making custom location tracking wrappers, be careful of using the .getLastKnownLocation() method as it only uses cached locations - you could end up sending the same location to the user every 30 seconds.
Good luck!

How to increase consistency of Android geofence enter/exit notifications?

I am using the built in geofence APIs (play services) and have been having mixed results. It looks like after setting a geofence, the notifications for entering/exiting are very inconsistent even when GPS is on, with an up-to-date location (LocationClient connected, running in the background.) I started monitoring (polling) location changes and distances in a debug text field, and saw that, even when based on the location registered by the device and the location of the geofence I am technically inside/outside of the geofence, notifications are sometimes triggered and sometimes not. Any way to make this more predictable? I am almost tempted to abandon this api and implement my own (battery draining) geofences based on polling of device location.
A couple of suggestions:
Make sure you're using a BroadcastReceiver and not a Service to receive the transitions, otherwise you will not/might not get it if your app gets killed/turned off. As discussed here:
Android Geofence eventually stop getting transition intents
Make sure you recreate your geofences after the device is rebooted, preferably using a boot-broadcast receiver. As discussed here:
Do Geofences remain active in android after a device reboot
One other common misconception, and which stumped me since it's different than IOS is that you'll always get a trigger immediately for a newly created geofence, if the device discovers that you're inside the geofence when creating it. I have solved this myself using a "grace period" for newly created geofences, which i explained in this thread:
addProximityAlert doesn't work as expected
Finally one important thing: Having your LocationClient connected in your app or not should not matter at all if you follow the points above. My process for adding or removing Geofences in my code is basically:
Create and connect locationclient.
In connect-callback, do adding/removing of geofence(s)
In geofence-result callback, disconnect locationclient.
Every time this happens, my location client is only connected a few seconds in total. The operating system will still produce geofence alerts and call my BroadcastReceiver whenever they happen.
If you do these things I bet your experience will improve.
Hope this helps!
I tried all the suggestions from the accepted response but the accurate wasn't better for my. If you are here looking more ideas you should read the following.
I was able manage the problem doing my own geofences algorithm based on android location api plus JTS Location Suite
To be more accurate. All you need is to create a jts polygon thats represent mathematically your fence.
static GeometryFactory GF = new GeometryFactory();
public Polygon getPolygon() {
ArrayList<Coordinate> coors = new ArrayList<>();
for (Point p : getPolygonPoints()) {
coors.add(new Coordinate(p.lat, p.lon));
}
// close the polygon is needs
final Coordinate first = coors.get(0);
final Coordinate last = coors.get(coors.size()-1);
if (!first.equals2D(last)) {
coors.add(coors.get(0));
}
// create polygon
return GF.createPolygon(coors.toArray(new Coordinate[] {}));
}
Then you can check whether if a current GPS point is inside or not of given polygon.
final Point point = GF.createPoint(new Coordinate(lat, lon));
if (point.within(getPolygon())) {
// hit
} else {
// miss
}
That's it all. Then you can create a java.util.Timer to periodically iterate a list of polygons (geo fences) to know which was hit or which was behind.
Note: Add the following in your module build.gradle to add JTS library in your project:
implementation(group: 'org.locationtech.jts.io', name: 'jts-io-common', version: '1.18.1') {
exclude(group: 'org.hamcrest')
}

Categories

Resources