onHandleWork never receives intent from pending intent Geofencing - android

I am working on a Geofencing application. The JobIntentService subclass that handles the GeofenceTransitions never receives the intent. I am receiving location updates at one minute interval then creating a new geofence list then adding the geofences based on a user's current location.
Here's my AndroidManifest.xml
........
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service
android:name=".GeofenceTransitionsService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE">
</service>
<receiver
android:name=".GeofenceBroadcastReceiver"
android:enabled="true"
android:exported="true" />
.............
My GeofenceBroadcastReceiver.java
public class GeofenceBroadcastReceiver extends BroadcastReceiver {
/**
* Receives incoming intents.
*
* #param context the application context.
* #param intent sent by Location Services. This Intent is provided to Location
* Services (inside a PendingIntent) when addGeofences() is called.
*/
#Override
public void onReceive(Context context, Intent intent) {
// Enqueues a JobIntentService passing the context and intent as parameters
GeofenceTransitionsService.enqueueWork(context, intent);
}
}
My GeofenceTransitionsService.java that handles the triggered geofences
public class GeofenceTransitionsService extends JobIntentService {
..........
/**
* Convenience method for enqueuing work in to this service
* Enqueue new work to be dispatched to onHandleWork
*/
public static void enqueueWork(Context context, Intent intent) {
Log.d(TAG, "Received intent: " + intent);
enqueueWork(context, GeofenceTransitionsService.class, JOB_ID, intent);
}
#Override
protected void onHandleWork(Intent intent){
// We have received work to do. The system or framework is already
// holding a wake lock for us at this point, so we can just go.
Log.d(TAG, "Received intent: " + intent);
}
}
Here's part of my code in PointOfInterestMapFragment.java that creates a geofencing request, creates the pending intent and adds the geofences
/* Use the GeofencingRequest class and its nested GeofencingRequestBuilder
* class to specify the geofences to monitor and to set how related geofence events are
* triggered
*/
private GeofencingRequest getGeofencingRequest(){
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
//tell Location services that GEOFENCE_TRANSITION_DWELL should be triggered if the
//device is already inside the geofence
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}//end method getGeofencingRequest
/*Pending intent that starts the IntentService*/
private PendingIntent getGeofencePendingIntent(){
Log.d(TAG, "getPendingIntent()");
//Reuse the pending intent if we already have it
if(mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(getActivity(), GeofenceBroadcastReceiver.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
mGeofencePendingIntent = PendingIntent.getBroadcast(getActivity()
, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}//end method PendingIntent
/*Add geofences*/
#SuppressWarnings("MissingPermission")
private void addGeofence(){
if(checkPermissions()){
mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Geofence added");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "Failed to add geofence: " + e.getMessage());
}
})
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//drawGeofence();
}
});
}else{
requestPermissions();
}
}//end method addGeofence
Here's the part of code in PointOfInterestMapFragment.java where I am receiving the location updates, populating the GeofenceList then adding geofences
/**
* Creates a callback for receiving location events.
*/
private void createLocationCallback() {
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mCurrentLocation = locationResult.getLastLocation();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
//populateGeofenceList to reflect the new current location bounds
populateGeofenceList();
addGeofence();
}
};
}
When the app executes, the I get the message in log cat from the line of code Log.d(TAG, "getPendingIntent()"); in getGeofencePendingIntent() but never get the message supposed to be displayed in onHandleWork() method

I had a similar 'problem'. The code is fine. In my case, I thought the code was not working because I had not understood properly how a geofence works. I thought to add the geofences, in your case a call to addGeofence() is the trigger, so I was waiting to see the notifications at that particular point in time. However a call to the method only adds the geofences for monitoring, then an intent is only delivered to the service when any of the filters are satisified (Geofence.GEOFENCE_TRANSITION_DWELL, Geofence.GEOFENCE_TRANSITION_EXIT OR Geofence.GEOFENCE_TRANSITION_ENTER) on an added geofence. You can read more from the documentation here
So, you might receive a Geofence added message in your log cat, but that's what it literally means, the geofences have been added not triggered. Wait for some time after the geofence have been added and if any of the filters are satisfied for a geofence that was added, then the intent is sent. So the solution that worked for me was to wait and I received the intent and notifications after some period of time.
If waiting does not work, you might want to extend the GEOFENCE_RADIUS, say to 3000 metres the check to see whether there is any change. Also, set the expiration duration to a higher value or to Geofence.NEVER_EXPIRE

Related

Geofence pending intent firing too late when device is in deep sleep (doze) mode

I need to notify user when he is near by given place. I use Geofencing API for this. When i test app on Android emulator with mock location everything works fine. Same for real device with Mock Location. But when I walk and my phone is in deep sleep mode Geofence fires after 5 - 10 min. If i am inside geofences radius and I unlock my phone, open any app which use location my geofence triggers immediately. (Android 5.1, Motorolla moto G 1-st generation)
Below is the way, how I registered my geofence:
public void registerLocation(RegisterAlarmRequestModel data) {
if (isLocationDetectionAllowed() && isConnected) {
GeofencingRequest geofencingRequest = prepareGeofencingRequest(prepareGeofence(data));
PendingIntent pendingIntent = prepareIntent(data.getId());
PendingResult<Status> result = GeofencingApi.addGeofences(
googleApiClient, geofencingRequest, pendingIntent);
Status status = result.await();
if (status.isSuccess())
Log.d("Location", "Geofence " + data.getId() + " has been registered");
}
}
//preparing Geofence Pending Intent which will be triggered
private PendingIntent prepareIntent(int alarmId) {
Intent intent = new Intent(context, LocationRingingService.class);
intent.putExtra(LocationRingingService.KEY_ALARM_ID, alarmId);
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private GeofencingRequest prepareGeofencingRequest(Geofence geofence) {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.addGeofence(geofence);
return builder.build();
}
private Geofence prepareGeofence(RegisterAlarmRequestModel data) {
Geofence geofence = new Geofence.Builder()
.setRequestId(String.valueOf(data.getId()))
.setCircularRegion(data.getLatitude(), data.getLongitude(), data.getRadius())
.setLoiteringDelay(100)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build();
return geofence;
}
For receiving intent I am using IntentService:
#Override
protected void onHandleIntent(Intent intent) {
Log.d("Location", "accepted intent: " + intent.toString());
//database request
}
This is how i have registered my service in manifest:
<service
android:name=".plugin.delivery.ringing.location.service.LocationRingingService"
android:enabled="true"
android:exported="true" />
Update: I need catch the moment when user just entered into geofence as accurate as possible. I have one idea: register geofence with radius greater than need (for example if need 100m radius, register geofence with 200-300m radius). And when user enters into Geophence with larger radius - start service with location udating to improve geofencing precision. And when user just entered - disable location service.
The problem is that when your phone is in deep sleep it is not updating the location accurately. The most accurate way to update location is GPS, and this is also the most battery-intensive. Other ways to update your location, such as using the cellular network, will consume less battery but are also less accurate. By default, geofences want to be really sure you are in the geofence before sending the intent. It is hard to get this sort of accuracy when in deep sleep because the phone is not getting accurate location data.
The reason why the geofence triggers immediately when you unlock your phone and use a location-aware app, is that the app updates the LastLocation, which your geofence sees and then sends the intent. While your phone is in deep sleep the location is not being updated.
With geofences there are also a few settings you can tweak to improve responsiveness. I see you're already using setLoiteringDelay, try playing around with different values , maybe try very small values and see what happens. You could also set a value for setNotificationResponsiveness, which works in a similar way. Doing that should make your fence more responsive, but it may cost more battery life. Also read the API Reference for setLoiteringDelay and setNotificationResponsiveness. Also read the geofence troubleshooting section if you haven't.
You could also increase the size of the geofence, try doubling it and then test. Since your location accuracy is low while in deep sleep, this will make it easier for your phone to be sure that it is inside the geofence, and once it's sure it is inside the geofence it will send the intent.
I hope this helps!
To improve it, Let's perform some checks
1) Use broadcast receiver to get it triggered easily instead of service. And set priority with intent-filter.
For e.g
<receiver
android:name=".youpackage.GeoReceiver"
android:exported="true">
<intent-filter android:priority="999">
<action android:name="yourpackage.ACTION_RECEIVE_GEOFENCE" />
</intent-filter>
</receiver>
And your pending intent will be :
Intent intent = new Intent("yourpackage.ACTION_RECEIVE_GEOFENCE");
PendingIntent pendingIntent = PendingIntent.getBroadcast(
youractivity,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
2) As your GPS goes in sleep mode, we need to wake it up while creating Geofence. Once you create your geofence, you can start pinging your GPS until you will get ENTER transition. This would must help to get triggering it.
public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
GoogleApiClient mGoogleApiClient;
LocationRequest locationRequest;
public GPSService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
Utility.ReadAndWriteData(this, Utility.readFileName(this), "Still Geofence is not triggered!!!");
}
#Override
public void onConnected(Bundle bundle) {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setFastestInterval(1000);
locationRequest.setInterval(2000);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,locationRequest,this);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onDestroy() {
super.onDestroy();
if(mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
And don't forgot to stop this service immediately when you get ENTER transition or It cause drain battery. This service is only to wake GPS up from sleep mode.

Starting an ActivityRecognitionService from within another active Service

I am having an issue getting my ActivityRecognition Service to remain running. I currently have a service (GService) that runs continuously in the background. I want to start the ActivityRecognition service within GService, and have the ActivityRecognition service broadcast the activity result back to GService. I am able to start the service and receive feedback that it is running, and I also get one result from the intent handler (no actual data), but never again.
Here is the section of code from my continuous service setting up the intent, pending intent:
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
//start process to receive activity updates
Intent intent = new Intent(this, DetectedActivitiesIntentService.class);
PendingIntent mActivityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, ActivityConstants.DETECTION_INTERVAL_MILLISECONDS_MOVING,
mActivityRecognitionPendingIntent).setResultCallback(this);
startService(intent); // this should start the DetectedActivitiesIntentService
This is the Broadcast receiver within GService:
public class ActivityDetectionBroadcastReceiver extends BroadcastReceiver {
protected static final String TAG_AR = "ADRR";
#Override
public void onReceive(Context context, Intent intent){
//ArrayList<DetectedActivity> updatedActivities =
// intent.getParcelableArrayListExtra(ActivityConstants.ACTIVITY_EXTRA);
//updateDetectedActivitiesList(updatedActivities);
String action = intent.getAction();
if(action.equals("com.gt.useractivity"))
{
Log.d(TAG_AR, "received broadcast from Activity service");
// below line should grab the resulting string activity from the intent and log it.
Log.d(TAG_AR, "activity is : " + intent.getExtras().getString(ActivityConstants.ACTIVITY_EXTRA));
}
}
}
Here is the ActivityRecognition Service code:
public class DetectedActivitiesIntentService extends IntentService {
protected static final String TAG = "ADIS";
/**
* This constructor is required, and calls the super IntentService(String)
* constructor with the name for a worker thread.
*/
public DetectedActivitiesIntentService() {
// Use the TAG to name the worker thread.
super(TAG);
Log.d(TAG, "Activity service started....");
}
#Override
public void onCreate() {
super.onCreate();
}
/**
* Handles incoming intents.
* #param intent The Intent is provided (inside a PendingIntent) when requestActivityUpdates()
* is called.
*/
#Override
protected void onHandleIntent(Intent intent) {
if(ActivityRecognitionResult.hasResult(intent))
{
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
Intent localIntent = new Intent(ActivityConstants.BROADCAST_ACTION);
// Get the list of the probable activities associated with the current state of the
// device. Each activity is associated with a confidence level, which is an int between
// 0 and 100.
ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
// Log each activity.
Log.i(TAG, "activities detected");
for (DetectedActivity da: detectedActivities) {
Log.i(TAG, ActivityConstants.getActivityString(da.getType()) + " " + da.getConfidence() + "%");
}
String activity = result.getMostProbableActivity().toString(); // get the activity and convert to string
// Broadcast the list of detected activities.
//localIntent.putExtra(ActivityConstants.ACTIVITY_EXTRA, detectedActivities);
//localIntent.setAction("com.gt.useractivity");
localIntent.putExtra(ActivityConstants.ACTIVITY_EXTRA, activity); // set the activity string to be transmitted
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
else{
Log.d(TAG, "Intent had no activity data....");
}
}
}
This Activity recognition sample is based from the Google Github sample.
All the examples I have found when using the PendingIntent is being called from a main activity, not from a service. I'm obviously doing something incorrect, but I can't figure it out. Any advice would be appreciated. I should also note that I have 2 broadcast receivers within my GService. I don't know if this would cause an issue or not.
It looks like I have solved the problem. I have a second intent within my GService used for broadcasting. From what I can tell from this thread (Pending intent works correctly for first notification but not for the rest) if there are multiple intents being used, they have to be unique. Thus, I added one line of code when declaring my intent intent.setAction(Long.toString(System.currentTimeMillis())); which is enough to differentiate it from the other intent to the system. Once I did that, I began to receive the Activity broadcasts from the intent service, as well as still receiving the location requests from within the GService routine.

Remove Geofence after triggered

I use Geofences in my app, everything works fine except the removal of triggered geofences.
I red the guide from the official documentation of Android but they don't explain how to remove a geofence inside of the IntentService.
Here is the code of the event handler of the service:
#Override
protected void onHandleIntent(Intent intent)
{
Log.e("GeofenceIntentService", "Location handled");
if (LocationClient.hasError(intent))
{
int errorCode = LocationClient.getErrorCode(intent);
Log.e("GeofenceIntentService", "Location Services error: " + Integer.toString(errorCode));
}
else
{
int transitionType = LocationClient.getGeofenceTransition(intent);
if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER)
{
List <Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
String[] triggerIds = new String[triggerList.size()];
for (int i = 0; i < triggerIds.length; i++)
{
// Store the Id of each geofence
triggerIds[i] = triggerList.get(i).getRequestId();
Picture p = PicturesManager.getById(triggerIds[i], getApplicationContext());
/* ... do a lot of work here ... */
}
}
else
Log.e("ReceiveTransitionsIntentService", "Geofence transition error: " + Integer.toString(transitionType));
}
}
How can I delete the geofence after he got triggered ?
You can do something like this:
LocationServices.GeofencingApi.removeGeofences(
mGoogleApiClient,
// This is the same pending intent that was used in addGeofences().
getGeofencePendingIntent()
).setResultCallback(this); // Result processed in onResult().
And your getGeofencePendingIntent() method can look like this:
/**
* Gets a PendingIntent to send with the request to add or remove Geofences. Location Services
* issues the Intent inside this PendingIntent whenever a geofence transition occurs for the
* current list of geofences.
*
* #return A PendingIntent for the IntentService that handles geofence transitions.
*/
private PendingIntent getGeofencePendingIntent() {
Log.d(TAG, "getGeofencePendingIntent()");
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(mContext, GeofenceIntentServiceStub.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
// addGeofences() and removeGeofences().
mGeofencePendingIntent = PendingIntent.getService(mContext, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}
You would proceed as you did when adding Geofences (create a LocationClient and wait for it to connect). Once it is connected, in the onConnected callback method, you would call removeGeofences on the LocationClient instance instead and pass it a list of request IDs you want to remove and an instance of OnRemoveGeofencesResultListener as a callback handler.
Of course, you must use the same request IDs you used when creating the GeoFence with GeoFence.Builder's setRequestId.
#Override
public void onConnected(Bundle arg0) {
locationClient.removeGeofences(requestIDsList,
new OnRemoveGeofencesResultListener() {
...
});

Pending Intents not fired

I'm trying to implement a Geofencing mechanism where a geofence is monitored and once the user exits the current geofence, the current co-ordinates are used to create a new geofence and db query is initiated for fetching some data.
My problem is that the pending intent is never fired.
From the logs i can see that the geofences are being added into the location client. However no pending intents are fired upon location change.(i've set the fence radius at 2m and i've walked over 100mts). Is there something wrong in the way i've declared the intent service ?
Here is the intent service class.
public class GeoFenceIntentService extends IntentService{
private static final String mIntentName = "GeoFenceIntentService";
public GeoFenceIntentService() {
super(mIntentName);
}
#Override
protected void onHandleIntent(Intent intent) {
int transitionType = LocationClient.getGeofenceTransition(intent);
Log.e(TAG,"Inside fence handler");
if(transitionType == Geofence.GEOFENCE_TRANSITION_EXIT){
//Query DB here with current co-ords
//create new GeoFence
Location location = LocationHelper.getInstance(mContext).getLastLocation();
mLat = String.valueOf(location.getLatitude());
mLong = String.valueOf(location.getLongitude());
addGeofenceToMonitor(location);
queryDb();
}
}
}
Also here is where i add the pending intents and the geofence to the location client
addGeofenceToMonitor(Location location){
List<Geofence> list = new ArrayList<Geofence>();
list.add(getNewGeofence(location.getLatitude(), location.getLongitude()));
PendingIntent pendingIntent = PendingIntent.getService(mContext, 0,
new Intent(mContext,GeoFenceIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT);
OnRemoveGeofencesResultListener removeListener = new OnRemoveGeofencesResultListener() {
#Override
public void onRemoveGeofencesByRequestIdsResult(int statusCode, String[] requestIDs) {
//To be used
}
#Override
public void onRemoveGeofencesByPendingIntentResult(int statusCode,PendingIntent pendingIntent) {
//Not used
}
};
LocationHelper.getInstance(mContext).removeGeoFence(mGeofenceRequestIDs, removeListener);
OnAddGeofencesResultListener addListener = new OnAddGeofencesResultListener() {
#Override
public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {
if(statusCode != LocationStatusCodes.SUCCESS){
//handle error cases
}
else
Log.i(TAG, "Successfully added Geofence "+geofenceRequestIds[0]+" for monitoring");
}
};
LocationHelper.getInstance(mContext).addGeoFence(list, pendingIntent, addListener);
}
Here is the snippet from the manifest file
<service
android:name="com.myexample.sample.GeoFenceIntentService"
android:label="#string/app_name"
android:exported="true">
</service>
Read this.
Have you checked the position estimation circle you are getting? You can use mock locations app to set the position as well as the accuracy circle. Your geofence may be too small to accommodate your position circle and that is why the events are not triggered.
Android GeoFences never enable the GPS (because their API is awful and their device power consumption is already so out of hand). You have to set up your geofences and then constantly poll the GPS separately if you want geofencing over GPS.
The handler of the GPS polling can be null, the poll only exists to force accurate information into their awful location API and in turn trigger the fences.

Android geofence with mock location provider

I have started developing on Android with last Location services feature : Geofences !! Is there any known problem with mock location provider ? Following example here (https://developer.android.com/training/location/geofencing.html) my intent service never fired even if the current location is inside geofence. I'm using FakeGPS android app as mock location provider and if I simulate a route I see the location changes on Google Maps app, so the mock location provider is working well. Any ideas ?
Thanks.
Paolo.
I tried forever to get this to work. What a pain Google! Since it says geofences can easily be tested using mocks.
The magic trick is to use the provider name "network" in the Location passed to setMockLocation.
Location location = new Location("network");
location.setLatitude(latitude);
location.setLongitude(longitude);
location.setTime(new Date().getTime());
location.setAccuracy(3.0f);
location.setElapsedRealtimeNanos(System.nanoTime());
LocationServices.FusedLocationApi.setMockLocation(_googleApiClient, location);
Actually Intent service used in the mentioned example works good if your app is in foreground but when the app is in background, this IntentService is never called.So we need to use Broadcast-Receiver instead of Intent service.
I found this blog helpful in getting solution.
http://davehiren.blogspot.in/2015/01/android-geofence-stop-getting.html
Geofences use FusedLocationProviderApi so to mock them you have to use FusedLocationProviderApi.setMockLocation
Make sure to enable mock locations on your phone. Select Settings->Developer Options->"Allow mock locations".
LocationServices.FusedLocationApi.setMockMode(googleApiClient, true)
needs to be used before setting Mock Location.
You can use broadcast receiver instead of activity like this
public class GeofenceReceiver extends BroadcastReceiver
implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
ResultCallback<Status>{
GoogleApiClient mGoogleApiClient;
PendingIntent mGeofencePendingIntent ;
Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
try {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
// The GeofenceRequest object.
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this); // Result processed in onResult().
} catch (SecurityException securityException) {
Log.i(getClass().getSimpleName(),securityException.getMessage());
}
}
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
/**
* Runs when the result of calling addGeofences() and removeGeofences() becomes available.
* Either method can complete successfully or with an error.
*
* Since this activity implements the {#link ResultCallback} interface, we are required to
* define this method.
*
* #param status The Status returned through a PendingIntent when addGeofences() or
* removeGeofences() get called.
*/
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
Log.i(getClass().getSimpleName(),"Success");
} else {
// Get the status code for the error and log it using a user-friendly message.
Log.i(getClass().getSimpleName(),getErrorString(status.getStatusCode()));
}
}
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_DWELL);
builder.addGeofences(getGeofecne());
return builder.build();
}
private List<Geofence> getGeofecne(){
List<Geofence> mGeofenceList = new ArrayList<>();
//add one object
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId("key")
// Set the circular region of this geofence.
.setCircularRegion(
25.768466, //lat
47.567625, //long
50) // radios
// Set the expiration duration of the geofence. This geofence gets automatically
// removed after this period of time.
//1000 millis * 60 sec * 5 min
.setExpirationDuration(1000 * 60 * 5)
// Set the transition types of interest. Alerts are only generated for these
// transition. We track entry and exit transitions in this sample.
.setTransitionTypes(
Geofence.GEOFENCE_TRANSITION_DWELL)
//it's must to set time in millis with dwell transition
.setLoiteringDelay(3000)
// Create the geofence.
.build());
return mGeofenceList;
}
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(mContext, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(mContext, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
}
}
check out my repo, there is a full example of using geofence
https://github.com/3zcs/Geofence

Categories

Resources