Android Geo-fence not working properly - android

I am using geofence api for proximity but it is not working properly. some times it gives in range and out range at the same location.
i am also using GPS library to improve accuracy of geofence inrange-outrange but still it is not working properly. i am using below code for geofence :
I am using 300 meters radius for considering inrange-outrange (enter-exit)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.geofencedemo">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CheckPermission"
android:screenOrientation="portrait"
android:theme="#style/DialogActivity" />
<receiver
android:name="services.GeofenceTransitionsReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.geofencedemo.ACTION_RECEIVE_GEOFENCE" />
<category android:name="com.geofencedemo" />
</intent-filter>
</receiver>
<service
android:name="services.GeofenceTransitionsIntentService"
android:exported="false" />
</application>
MainActivity.java (for registering geofence)
public class MainActivity extends Activity implements com.google.android.gms.location.LocationListener {
private LocationManager locationManager;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private final float GEOFENCE_RADIUS_IN_METERS = 300;//Meter(s)
private final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = Geofence.NEVER_EXPIRE;
private int GEOFENCE_TRANSITION_ENTER = 1;
private int GEOFENCE_TRANSITION_EXIT = 2;
private List<Geofence> mGeofenceList;
private String geofenceID = "testGeofence";
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences("ISSKEYGEOFENCE-prefs", MODE_PRIVATE);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Button btnSetLocation = (Button) findViewById(R.id.btn_setlocation);
btnSetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
Toast.makeText(getApplicationContext(), "Please enable Location service to allow set location", Toast.LENGTH_LONG).show();
return;
}
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1){
Log.d("myTag", "check marshmallow permission...");
Intent permissionIntent = new Intent(MainActivity.this, CheckPermission.class);
startActivityForResult(permissionIntent, 1111);
} else {
intGoogleAPI();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1111:
if (resultCode == RESULT_OK) {
intGoogleAPI();
}
break;
}
}
private void intGoogleAPI() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(1000);
mGeofenceList = new ArrayList<Geofence>(1);
mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(final Bundle bundle) {
if (isServiceConnected()) {
Log.d("myTag", "request for update current location");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
}
}
#Override
public void onConnectionSuspended(final int cause) {}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(final ConnectionResult connectionResult) {}
}).build();
mGoogleApiClient.connect();
}
private boolean isServiceConnected() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this);
return ConnectionResult.SUCCESS == resultCode;
}
#Override
public void onLocationChanged(Location mLastLocation) {
if (isServiceConnected()) {
Log.d("myTag", "request removed location update");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
try {
addLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude());
} catch (Exception e) {}
}
public void addLocation(final double latitude, final double longitude) {
Log.v("myTag", "set lcation lat: " + latitude);
Log.v("myTag", "set lcation lag: " + longitude);
mGeofenceList.add(new Geofence.Builder().setRequestId(geofenceID).setTransitionTypes(GEOFENCE_TRANSITION_ENTER | GEOFENCE_TRANSITION_EXIT).setCircularRegion(latitude, longitude, GEOFENCE_RADIUS_IN_METERS).setExpirationDuration(GEOFENCE_EXPIRATION_IN_MILLISECONDS).build());
final List<String> GEO_FENCE_ID_LIST = new ArrayList<String>();
GEO_FENCE_ID_LIST.add(geofenceID);
if (mGoogleApiClient != null) {
LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient, GEO_FENCE_ID_LIST).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(final Status status) {
if (status.isSuccess()) {
// successfully removed geofence...
Log.d("myTag", "removed old geofence successfully ");
} else {
Log.d("myTag", "Not removed old geofence");
}
}
});
}
if (mGoogleApiClient != null) {
LocationServices.GeofencingApi.addGeofences(mGoogleApiClient, getGeofencingRequest(), getGeofencePendingIntent()).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(final Status status) {
if (status.isSuccess()) {
// successfully Added geofence...
Log.d("myTag", "New geofence successfully added");
Toast.makeText(getApplicationContext(), "Successfully added geofence", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("isinrange", false);
editor.putString("lat", String.valueOf(latitude));
editor.putString("log", String.valueOf(longitude));
editor.apply();
}
try {
if (isServiceConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);
}
mGoogleApiClient.disconnect();
} catch (Exception e) {}
}
});
}
}
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_EXIT);
builder.addGeofences(mGeofenceList);
return builder.build();
}
private PendingIntent getGeofencePendingIntent() {
Intent intent = new Intent("com.geofencedemo.ACTION_RECEIVE_GEOFENCE");
return PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
GeofenceTransitionsIntentService (Trigger inrange,outrange by geofence)
public class GeofenceTransitionsIntentService extends IntentService implements com.google.android.gms.location.LocationListener {
public GeofenceTransitionsIntentService() {
super("GeofenceTransitionsIntentService");
}
#Override
public void onCreate() {
super.onCreate();
preferences = getSharedPreferences("ISSKEYGEOFENCE-prefs", MODE_PRIVATE);
}
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private boolean isLocationFetched = false;
private String geofenceTransitionIds;
private boolean isInRange = false;
private SharedPreferences preferences;
#Override
protected void onHandleIntent(final Intent intent) {
if (intent.getExtras() != null) {
int geofenceTransitionType = intent.getIntExtra("TransitionType", 4);
geofenceTransitionIds = intent.getStringExtra("TransitionId");
/*final String lat = intent.getStringExtra("TransitionId_lat");
final String log = intent.getStringExtra("TransitionId_log");*/
if (geofenceTransitionIds != null && geofenceTransitionIds.length() > 0) {
switch (geofenceTransitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
geofenceTransitionIds(geofenceTransitionIds, true);
//new IntGoogleApiClient(appStorage, null, true).Intialize();
//processIn(geofenceTransitionIds, lat, log);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
geofenceTransitionIds(geofenceTransitionIds, false);
//new IntGoogleApiClient(appStorage, null, true).Intialize();
//processOut(geofenceTransitionIds, lat, log);
break;
}
}
}
}
private void geofenceTransitionIds (String geofenceTransitionIds, boolean isEnteCall) {
if (geofenceTransitionIds != null && geofenceTransitionIds.length() > 0) {
isInRange = isEnteCall;
intGoogleAPI();
}
}
private void intGoogleAPI() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(1000);
mGoogleApiClient = new GoogleApiClient.Builder(GeofenceTransitionsIntentService.this).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(final Bundle bundle) {
if (isServiceConnected()) {
// please consider here location permission is already allowed...
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, GeofenceTransitionsIntentService.this);
}
}
#Override
public void onConnectionSuspended(final int cause) {}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(final ConnectionResult connectionResult) {}
}).build();
mGoogleApiClient.connect();
}
private boolean isServiceConnected() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(GeofenceTransitionsIntentService.this);
return ConnectionResult.SUCCESS == resultCode;
}
#Override
public void onLocationChanged(Location passedLocation) {
if (passedLocation != null && !isLocationFetched) {
if (isServiceConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, GeofenceTransitionsIntentService.this);
}
isLocationFetched = true;
try {
if (geofenceTransitionIds != null && geofenceTransitionIds.length() > 0) {
if (isInRange) {
processIn(geofenceTransitionIds, String.valueOf(passedLocation.getLatitude()), String.valueOf(passedLocation.getLongitude()));
} else {
processOut(geofenceTransitionIds, String.valueOf(passedLocation.getLatitude()), String.valueOf(passedLocation.getLongitude()));
}
}
} catch (Exception e) {}
disconnectGoogleClient();
}
}
private void disconnectGoogleClient() {
try {
if (mGoogleApiClient != null) {
if (isServiceConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, GeofenceTransitionsIntentService.this);
}
mGoogleApiClient.disconnect();
}
} catch (Exception e) {}
}
private void processIn(String passedIds, String lat, String log) {
if (passedIds != null) {
List<String> items = Arrays.asList(passedIds.split("\\s*,\\s*"));
for (String deviceName : items) {
if (deviceName != null) {
boolean isOutRange = preferences.getBoolean("isinrange", false);
if (mappingRadius(true, deviceName, lat, log) && isOutRange) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("isinrange", false);
editor.apply();
sendNotification(GeofenceTransitionsIntentService.this, "In range come!", Color.BLACK);
}
}
}
}
}
private void processOut(String passedIds, String lat, String log) {
if (passedIds != null) {
List<String> items = Arrays.asList(passedIds.split("\\s*,\\s*"));
for (String deviceName : items) {
if (deviceName != null) {
boolean isInRange = preferences.getBoolean("isinrange", false);
if (mappingRadius(false, deviceName, lat, log) && !isInRange) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("isinrange", true);
editor.apply();
sendNotification(GeofenceTransitionsIntentService.this, "Out range come!", Color.RED);
}
}
}
}
}
private boolean mappingRadius(boolean isInRange, String deviceName, String currentLat, String currentLog) {
final float cLat = Float.parseFloat(currentLat);
final float cLog = Float.parseFloat(currentLog);
Log.d("myTag", "GeofenceTransitionsReceiver lat " + cLat);
Log.d("myTag", "GeofenceTransitionsReceiver log " + cLog);
float appLat;
float appLog;
appLat = Float.parseFloat(preferences.getString("lat", "0.0"));
appLog = Float.parseFloat(preferences.getString("log", "0.0"));
Log.d("myTag", "GeofenceTransitionsReceiver app lat " + appLat);
Log.d("myTag", "GeofenceTransitionsReceiver app log " + appLog);
Location current_latlog = new Location("crntlocation");
current_latlog.setLatitude(appLat);
current_latlog.setLongitude(appLog);
Location new_latlog = new Location("newlocation");
new_latlog.setLatitude(cLat);
new_latlog.setLongitude(cLog);
final double distance = current_latlog.distanceTo(new_latlog);
Log.v("myTag", "GeofenceTransitionsReceiver calculation distance is: " + distance);
//if (distance < 2000) {
if (isInRange) {
if (distance <= 300) { // with in 300 Meters consider as in range...
return true;
} else {
return false;
}
} else {
if (distance >= 300) { // more than 300 Meters consider as out range...
return true;
} else {
return false;
}
}
/*} else {
return false;
}*/
}
private void sendNotification(final Context context, String notificationMessage, int color) {
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(new Intent());
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)).setContentTitle(context.getResources().getString(R.string.app_name)).setTicker(notificationMessage).setContentText(notificationMessage).setContentIntent(notificationPendingIntent).setColor(color).setVibrate(new long[] { 1000, 1000, 1000, 1000 }).setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify((int) System.currentTimeMillis(), builder.build());
}
}
GeofenceTransitionsReceiver (handling/calculate distance after geofence trigger)
public class GeofenceTransitionsReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = getErrorString(context, geofencingEvent.getErrorCode());
Log.d("myTag", "GeofenceTransitionsReceiver error " +errorMessage);
// sendNotification(context, errorMessage, Color.RED);
return;
}
int geofenceTransition = geofencingEvent.getGeofenceTransition();
Log.d("myTag", "GeofenceTransitionsReceiver " + geofenceTransition);
// for testing....
//sendNotification(context, context.getResources().getString(R.string.geofence_transition_type, geofenceTransition), Color.RED);
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
String geofenceTransitionIds = getGeofenceTransitionIds(triggeringGeofences);
Location triggeringLocation = geofencingEvent.getTriggeringLocation();
Intent serviceIntent = new Intent(context.getApplicationContext(), GeofenceTransitionsIntentService.class);
serviceIntent.putExtra("TransitionType", geofenceTransition);
serviceIntent.putExtra("TransitionId", geofenceTransitionIds);
serviceIntent.putExtra("TransitionId_lat", String.valueOf(triggeringLocation.getLatitude()));
serviceIntent.putExtra("TransitionId_log", String.valueOf(triggeringLocation.getLongitude()));
context.startService(serviceIntent);
} else {
// sendNotification(context,
// context.getResources().getString(R.string.geofence_transition_invalid_type,
// geofenceTransition), Color.RED);
}
}
private String getErrorString(final Context context, int errorCode) {
Resources mResources = context.getResources();
switch (errorCode) {
case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
return "Geofence service is not available now";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
return "Your app has registered too many geofences";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
return "You have provided too many PendingIntents to the addGeofences() call";
default:
return "Unknown error: the Geofence service is not available now";
}
}
private String getGeofenceTransitionIds(List<Geofence> triggeringGeofences) {
List<String> triggeringGeofencesIdsList = new ArrayList<String>();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
return TextUtils.join(",", triggeringGeofencesIdsList);
}
}
Is there anything else we can do to improve accuracy and overcome the problem of inrange outrange at the same location ?

Related

Location not updated on 10 mins of interval

I want to track the user location. So I have made a code so that on every 10 mins of interval its location should be hit on server. If it is not moving also the location should hit at 10 min of interval. I set Location interval minutes for 10 min public static final long LOCATION_INTERVAL_MINUTES = 10 * 60 * 1000;
It should update the location with 10 min, but it hits randomly. I also increase the gps frequency distance from 10 to gpsFreqInDistance = 100 .Random hits are stopped but it will not updated on 10 mins of interval.
So what to do to get location at 10 min of interval.
Below is my manifiest
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
As for Android above 10version u cant use background location and foreground location simultaneously. So i comment the ACCESS_BACKGROUND_LOCATION" in my project.
public class LocationMonitoringService implements LocationListener, GpsStatus.Listener {
private static final String TAG = LocationMonitoringService.class.getSimpleName();
private Context mContext;
private LocationRepository mLocationRepository;
private ShareLocationAdapterClass mAdapter;
private SyncOfflineRepository syncOfflineRepository;
private long updatedTime = 0;
private List<UserLocationPojo> mUserLocationPojoList;
private SyncOfflineAttendanceRepository syncOfflineAttendanceRepository;
public LocationMonitoringService(final Context context) {
mContext = context;
mLocationRepository = new LocationRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineRepository = new SyncOfflineRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineAttendanceRepository = new SyncOfflineAttendanceRepository(AUtils.mainApplicationConstant.getApplicationContext());
mUserLocationPojoList = new ArrayList<>();
mAdapter = new ShareLocationAdapterClass();
mAdapter.setShareLocationListener(new ShareLocationAdapterClass.ShareLocationListener() {
#Override
public void onSuccessCallBack(boolean isAttendanceOff) {
if (isAttendanceOff && !syncOfflineAttendanceRepository.checkIsAttendanceIn()) {
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
}
}
#Override
public void onFailureCallBack() {
}
});
}
public void onStartTacking() {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
//Exception thrown when GPS or Network provider were not available on the user's device.
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(false);
criteria.setBearingRequired(false);
//API level 9 and up
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
int gpsFreqInDistance = 100;
assert locationManager != null;
locationManager.addGpsStatusListener(this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this, null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this, null);
} catch (IllegalArgumentException | SecurityException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
Log.d(TAG, "onStartTacking: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (RuntimeException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
e.printStackTrace();
}
}
public void onStopTracking() {
mAdapter.shareLocation();
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
/*
* LOCATION CALLBACKS
*/
//to get the location change
#Override
public void onLocationChanged(Location location) {
Log.d("okh ", "onLocationChanged: "+System.currentTimeMillis());
if (location != null) {
Log.d(TAG, String.valueOf(location.getAccuracy()));
if (!AUtils.isNullString(String.valueOf(location.getLatitude())) && !AUtils.isNullString(String.valueOf(location.getLongitude()))) {
Prefs.putString(AUtils.LAT, String.valueOf(location.getLatitude()));
Prefs.putString(AUtils.LONG, String.valueOf(location.getLongitude()));
if (Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY, false)) {
if (updatedTime == 0) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
if ((updatedTime + AUtils.LOCATION_INTERVAL_MINUTES) <= System.currentTimeMillis()) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
sendLocation();
}
}
} else {
Log.d(TAG, "onLocationChanged: no location found !!");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged" + provider + "Status" + status);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, " onProviderEnabled" + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, " onProviderDisabled" + provider);
}
#Override
public void onGpsStatusChanged(int event) {
}
private void sendLocation() {
// mAdapter.shareLocation(getTempList());
Log.d("okh", "sendLocation: Current Time In Millies "+ System.currentTimeMillis());
try {
Calendar CurrentTime = AUtils.getCurrentTime();
Calendar DutyOffTime = AUtils.getDutyEndTime();
if (CurrentTime.before(DutyOffTime)) {
Log.i(TAG, "Before");
UserLocationPojo userLocationPojo = new UserLocationPojo();
userLocationPojo.setUserId(Prefs.getString(AUtils.PREFS.USER_ID, ""));
userLocationPojo.setLat(Prefs.getString(AUtils.LAT, ""));
userLocationPojo.setLong(Prefs.getString(AUtils.LONG, ""));
double startLat = Double.parseDouble(Prefs.getString(AUtils.LAT, "0"));
double startLng = Double.parseDouble(Prefs.getString(AUtils.LONG, "0"));
userLocationPojo.setDistance(String.valueOf(AUtils.calculateDistance(
AUtils.mainApplicationConstant.getApplicationContext(), startLat, startLng)));
// userLocationPojo.setDatetime(AUtils.getServerDateTime()); //TODO
userLocationPojo.setDatetime(AUtils.getServerDateTimeLocal());
userLocationPojo.setOfflineId("0");
if (AUtils.isInternetAvailable() && AUtils.isConnectedFast(mContext))
userLocationPojo.setIsOffline(true);
else
userLocationPojo.setIsOffline(false);
String UserTypeId = Prefs.getString(AUtils.PREFS.USER_TYPE_ID, AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI);
if (AUtils.isInternetAvailable()) {
TableDataCountPojo.LocationCollectionCount count = syncOfflineRepository.getLocationCollectionCount(AUtils.getLocalDate());
if ((UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI) || UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_WASTE_MANAGER))
&& (count.getLocationCount() > 0 || count.getCollectionCount() > 0)) {
syncOfflineRepository.insetUserLocation(userLocationPojo);
} else {
mUserLocationPojoList.add(userLocationPojo);
mAdapter.shareLocation(mUserLocationPojoList);
mUserLocationPojoList.clear();
}
} else {
if (UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_EMP_SCANNIFY)) {
Type type = new TypeToken<UserLocationPojo>() {
}.getType();
mLocationRepository.insertUserLocationEntity(new Gson().toJson(userLocationPojo, type));
} else {
syncOfflineRepository.insetUserLocation(userLocationPojo);
}
mUserLocationPojoList.clear();
}
}
else {
Log.i(TAG, "After");
syncOfflineAttendanceRepository.performCollectionInsert(mContext,
syncOfflineAttendanceRepository.checkAttendance(), AUtils.getCurrentDateDutyOffTime());
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
Activity activity = ((Activity) AUtils.currentContextConstant);
if (activity instanceof DashboardActivity) {
((Activity) AUtils.currentContextConstant).recreate();
AUtils.DutyOffFromService = true;
}
if (!AUtils.isNull(AUtils.currentContextConstant)) {
((Activity) AUtils.currentContextConstant).recreate();
}
}
} catch (Exception e) {
e.printStackTrace();
}
Below is the foreground service which i have used
public class ForgroundService extends Service {
private LocationMonitoringService monitoringService;
private Handler locationHandler;
private Runnable locationThread;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
Log.d("okh", "onCreate: " +System.currentTimeMillis());
monitoringService = new LocationMonitoringService(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
Log.d("okh", "onCreate: " +System.currentTimeMillis());
Log.d("okh", "onStartCommand: ");
final int currentId = startId;
locationThread = new Runnable() {
public void run() {
monitoringService.onStartTacking();
}
};
locationHandler = new Handler(Looper.getMainLooper());
locationHandler.post(locationThread);
startLocationForeground();
return Service.START_STICKY;
// return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
//Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
locationHandler.removeCallbacks(locationThread);
monitoringService.onStopTracking();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
{
stopForeground(STOP_FOREGROUND_REMOVE);
}
if(Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY,false))
{
Intent broadcastIntent = new Intent(this, RestarterBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
}
}
private void startLocationForeground() {
if (Build.VERSION.SDK_INT >= 26) {
String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? this.createNotificationChannel("my_service", "My Background Service")
: "";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder((Context) this,
channelId);
Notification notification = notificationBuilder
.setOngoing(true)
.setContentText("Please don't kill the app from background. Thank you!!")
.setSmallIcon(getNotificationIcon(notificationBuilder))
.setPriority(-2)
.setCategory("service")
.build();
startForeground(101, notification);
}
}
#RequiresApi(26)
private String createNotificationChannel(String channelId, String channelName) {
NotificationChannel chan = new NotificationChannel(channelId, (CharSequence)channelName,
NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
service.createNotificationChannel(chan);
return channelId;
}
private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int color = 0x008000;
notificationBuilder.setColor(color);
return R.drawable.ic_noti_icon;
}
return R.drawable.ic_noti_icon;
}
}
Why you are passing null in the last parameter? Did you try without passing that?
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this, null);
First of all Google Location Services are far better than Traditional LocationManager to achieve this requirement.
https://developer.android.com/training/location/request-updates

Location update from a repetitive task not working when mobile screen goes off

I have made a location update foreground service which gets locations directly(requestLocationUpdates) when interval is less than 30 secs and if its more than 30 sec, I use ScheduledExecutorService to get the location result and pool location results to get the best location. Only issue I am facing is I am not getting location updates when screen goes off. This code is working well till mobile screen goes off.
Please take care its a foreground service.
My Code is as below:
private boolean currentlyProcessingLocation = false;
public static int intervalForLocationRequestMethod = 500;
public static int intervalForLocationUpdates = 30000;
public int locationUpdateMethodThreshold = 5000;
public int sameLocationCounter = 0;
boolean locationUpdateMethodChanged = false;
ScheduledExecutorService sch;
Runnable periodicTask = new Runnable() {
#Override
public void run() {
Log.i(TAG, "run: repeat ");
Intent i = new Intent(LocationService.this, LocationService.class);
i.setAction(Constants.ACTION.STARTLOCATIONREPEAT_ACTION);
startService(i);
}
};
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ");
buildGoogleApiClient();
if (intervalForLocationUpdates <= locationUpdateMethodThreshold) {
intervalForLocationRequestMethod = intervalForLocationUpdates;
}
showOnGoingLocationServiceNotification();
}
private void showOnGoingLocationServiceNotification() {
Log.i(TAG, "showOnGoingLocationServiceNotification: ");
Intent notificationIntent = new Intent(this, MapsActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MapsActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Forcee")
.setTicker("Forcee Tracking")
.setColor(Color.GREEN)
.setContentText("Forcee is tracking your location....Tap to stop")
.setSmallIcon(R.drawable.cast_ic_notification_small_icon)
.setWhen(System.currentTimeMillis())
.setContentIntent(resultPendingIntent)
.setOngoing(true).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setFastestInterval(intervalForLocationRequestMethod);
mLocationRequest.setInterval(intervalForLocationRequestMethod);
if (intervalForLocationUpdates <= locationUpdateMethodThreshold || locationUpdateMethodChanged) {
mLocationRequest.setSmallestDisplacement(50);
}
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
Thread thread = new Thread(new LocationUpdateThread(intent, startId));
thread.start();
return START_STICKY;
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
if (lastLocation != null) {
if (location.distanceTo(lastLocation) >= 40.0f && locationUpdateMethodChanged && location.getAccuracy() <= 100.0f) {
locationUpdateMethodChanged = false;
currentlyProcessingLocation = false;
sch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
sch.scheduleAtFixedRate(periodicTask, intervalForLocationUpdates, intervalForLocationUpdates, TimeUnit.MILLISECONDS);
}
}
if (location.getAccuracy() <= 100.0f) {
if (firstLocationUpdateCall) {
updatingLocation(location);
firstLocationUpdateCall = false;
} else {
if (location.distanceTo(lastLocation) >= 40.0f) {
updatingLocation(location);
sameLocationCounter = 0;
} else {
if (intervalForLocationUpdates > locationUpdateMethodThreshold && !locationUpdateMethodChanged) {
sameLocationCounter++;
lastLocation = location;
Log.i(TAG, "onLocationChanged: " + sameLocationCounter);
if (sameLocationCounter == 5) {
locationUpdateMethodChanged = true;
intervalForLocationRequestMethod = 1000;
stopLocationUpdates();
sameLocationCounter = 0;
sch.shutdownNow();
sch = null;
Intent i = new Intent(LocationService.this, LocationService.class);
i.setAction(Constants.ACTION.STARTLOCATIONREPEAT_ACTION);
startService(i);
}
Log.i(TAG, "onLocationChanged: " + locationUpdateMethodChanged);
}
}
if (intervalForLocationUpdates> locationUpdateMethodThreshold && !locationUpdateMethodChanged) {
stopLocationUpdates();
Log.i(TAG, "onLocationChanged: stopcheckshift");
}
}
}
}
public void updatingLocation(Location location) {
lastLocation = location;
Log.i(TAG, "onLocationChanged: First " + locationPoints.size());
locationPoints.add(location);
Log.i(TAG, "onLocationChanged: Last " + locationPoints.size());
sendLocationsToActivity(locationPoints);
if (intervalForLocationUpdates > locationUpdateMethodThreshold) {
stopLocationUpdates();
}
}
public void sendLocationsToActivity(ArrayList<Location> locationPoints) {
Log.i(TAG, "sendLocationsToActivity: ");
Intent intent = new Intent("LocationUpdates");
intent.putParcelableArrayListExtra("Locations", locationPoints);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void stopLocationUpdates() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, LocationService.this);
mGoogleApiClient.disconnect();
currentlyProcessingLocation = false;
}
}
final class LocationUpdateThread implements Runnable {
int service_id;
Intent intent;
LocationUpdateThread(Intent intent, int service_id) {
this.intent = intent;
this.service_id = service_id;
}
#Override
public void run() {
Log.i(TAG, "run: ");
if (intent != null) {
Log.i(TAG, "run: " + intent.getAction());
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
toastHandler("Tracking Started!");
mGoogleApiClient.connect();
currentlyProcessingLocation = true;
if (intervalForLocationUpdates > locationUpdateMethodThreshold) {
sch = Executors.newScheduledThreadPool(1);
sch.scheduleAtFixedRate(periodicTask, intervalForLocationUpdates, intervalForLocationUpdates, TimeUnit.MILLISECONDS);
}
} else if (intent.getAction().equals(Constants.ACTION.STARTLOCATIONREPEAT_ACTION)) {
if (!currentlyProcessingLocation) {
Log.i(TAG, "run: curt");
checkLocationSettings();
currentlyProcessingLocation = true;
mGoogleApiClient.connect();
}
} else if (intent.getAction().equals(Constants.ACTION.STOPFOREGROUND_ACTION)) {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, LocationService.this);
mGoogleApiClient.disconnect();
}
if (sch != null) {
sch.shutdownNow();
}
stopForeground(true);
stopSelf();
toastHandler("Tracking Stopped!");
}
}
}
void toastHandler(final String msg) {
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
public void run() {
Toast.makeText(LocationService.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
}

Geofences not working when app is killed

I know similar questions have been asked before but answers were not perfect.
I created an app with geofences using the sample code from android developer website. I did not use any shared preferences to store geofences as I am not removing the geofences. I am testing the app from within the geofence, but my smartphone receives notifications every time the app runs and no notifications are observed when the app is killed. Why does this happen? I think I am supposed to receive notifications even when the app is killed.
MainActivity
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_layout);
.....
GeofencingTask myTask = new GeofencingTask();
myTask.execute();
}
private class GeofencingTask extends AsyncTask<String,Void,String> implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
mGeofenceList = new ArrayList<Geofence>();
mGeofenceList.add(new Geofence.Builder()
.setRequestId("1")
.setCircularRegion(
Constants.MyAPP_LOCATION_LATITUDE,
Constants.MyAPP_LOCATION_LONGITUDE,
Constants.MyAPP_RADIUS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_TIME)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
return null;
}
protected void onPostExecute(String s) {
if (s == null) {
return;
}
}
#Override
public void onConnected(Bundle bundle) {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
);
Toast.makeText(MainActivity.this, "Starting gps", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(MainActivity.this,
Constants.CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while resolving connection error.", e);
}
} else {
int errorCode = connectionResult.getErrorCode();
Log.e(TAG, "Connection to Google Play services failed with error code " + errorCode);
}
}
}
GeofenceTransitionsIntentService.java
public class GeofenceTransitionsIntentService extends IntentService{
String TAG = "GeofenceTransitionsIntentService";
int geofenceTransition;
public GeofenceTransitionsIntentService() {
super("name");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
int errorCode = geofencingEvent.getErrorCode();
Log.e(TAG, "Location Services error: " + errorCode);
}
geofenceTransition = geofencingEvent.getGeofenceTransition();
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger
// multiple geofences.
List triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
Log.i("GeofenceTransitionDetails",geofenceTransitionDetails);
// Send notification and log the transition details.
sendNotification(geofenceTransitionDetails);
sendInOutsTask myTask = new sendInOutsTask();
myTask.execute();
Log.i(TAG, geofenceTransitionDetails);
} else {
// Log the error.
Log.e(TAG, getString(R.string.geofence_transition_invalid_type,
geofenceTransition));
}
}
private String getGeofenceTransitionDetails(
Context context,
int geofenceTransition,
List<Geofence> triggeringGeofences) {
String geofenceTransitionString = getTransitionString(geofenceTransition);
// Get the Ids of each geofence that was triggered.
ArrayList triggeringGeofencesIdsList = new ArrayList();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
return geofenceTransitionString;
}
/**
* Posts a notification in the notification bar when a transition is detected.
* If the user clicks the notification, control goes to the MainActivity.
*/
private void sendNotification(String notificationDetails) {
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.zemoso_logo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.mipmap.zemoso_logo))
.setColor(Color.RED)
.setContentTitle(notificationDetails)
.setContentText(getString(R.string.geofence_transition_notification_text))
.setContentIntent(notificationPendingIntent);
builder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
}
private String getTransitionString(int transitionType) {
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
return Constants.WELCOME_NOTIFICATION;
case Geofence.GEOFENCE_TRANSITION_EXIT:
return Constants.EXIT_NOTIFICATION;
default:
return null;
}
}
}
Ok, May be a bit late but I'll post the answer on how I fixed this issue myself. Two things:
1) I was adding the geofences every time I run the MainActivity and geofences API triggers the geofencing event, if you add the geofences when you are already inside the specified geofence (i.e. starting the geofence app when you are already inside the geofence).
So I changed my code in the onConnected method to add the geofences only if they are not added previously. (Implemented a check using Shared preferences)
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected to GoogleApiClient");
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("GEO_PREFS", Context.MODE_PRIVATE);
String geofencesExist = sharedPrefs.getString("Geofences added", null);
if (geofencesExist == null) {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent(this)
).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("GEO_PREFS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("Geofences added", "1");
editor.commit();
}
}
});
}
}
2) Turns out the reasons for not receiving notifications when the app is not available were
i) Either I toggled location services in the device(on/off/battery saving/device only/high accuracy) at least once after I added the geofences or,
ii) The device was rebooted.
To overcome this, I have added a broadcast receiver to listen to device reboots and location services toggling. In the receiver, I am adding the geofences again if the device either rebooted or location services toggled.
public class BootReceiver extends BroadcastReceiver implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> {
private static GoogleApiClient mGoogleApiClient;
private static List<Geofence> mGeofenceList;
private static PendingIntent mGeofencePendingIntent;
private static final String TAG = "BootReceiver";
Context contextBootReceiver;
#Override
public void onReceive(final Context context, Intent intent) {
contextBootReceiver = context;
SharedPreferences sharedPrefs;
SharedPreferences.Editor editor;
if ((intent.getAction().equals("android.location.MODE_CHANGED") && isLocationModeAvailable(contextBootReceiver)) || (intent.getAction().equals("android.location.PROVIDERS_CHANGED") && isLocationServciesAvailable(contextBootReceiver))) {
// isLocationModeAvailable for API >=19, isLocationServciesAvailable for API <19
sharedPrefs = context.getSharedPreferences("GEO_PREFS", Context.MODE_PRIVATE);
editor = sharedPrefs.edit();
editor.remove("Geofences added");
editor.commit();
if (!isGooglePlayServicesAvailable()) {
Log.i(TAG, "Google Play services unavailable.");
return;
}
mGeofencePendingIntent = null;
mGeofenceList = new ArrayList<Geofence>();
mGeofenceList.add(new Geofence.Builder()
.setRequestId("1")
.setCircularRegion(
Constants.MyAPP_LOCATION_LATITUDE,
Constants.MyAPP_LOCATION_LONGITUDE,
Constants.MyAPP_LOCATION_RADIUS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_TIME)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL |
Geofence.GEOFENCE_TRANSITION_EXIT)
.setLoiteringDelay(30000)
.build());
mGoogleApiClient = new GoogleApiClient.Builder(contextBootReceiver)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
private boolean isLocationModeAvailable(Context context) {
if (Build.VERSION.SDK_INT >= 19 && getLocationMode(context) != Settings.Secure.LOCATION_MODE_OFF) {
return true;
}
else return false;
}
public boolean isLocationServciesAvailable(Context context) {
if (Build.VERSION.SDK_INT < 19) {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return (lm.isProviderEnabled(LocationManager.GPS_PROVIDER) || lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
}
else return false;
}
public int getLocationMode(Context context) {
try {
return Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return 0;
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected to GoogleApiClient");
SharedPreferences sharedPrefs = contextBootReceiver.getSharedPreferences("GEO_PREFS", Context.MODE_PRIVATE);
String geofencesExist = sharedPrefs.getString("Geofences added", null);
if (geofencesExist == null) {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent(contextBootReceiver)
).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
SharedPreferences sharedPrefs = contextBootReceiver.getSharedPreferences("GEO_PREFS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("Geofences added", "1");
editor.commit();
}
}
});
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult((android.app.Activity) contextBootReceiver,
Constants.CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "Exception while resolving connection error.", e);
}
} else {
int errorCode = connectionResult.getErrorCode();
Log.i(TAG, "Connection to Google Play services failed with error code " + errorCode);
}
}
#Override
public void onResult(Status status) {
}
private boolean isGooglePlayServicesAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(contextBootReceiver);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, (android.app.Activity) contextBootReceiver,
Constants.PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
static GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL);
builder.addGeofences(mGeofenceList);
return builder.build();
}
static PendingIntent getGeofencePendingIntent(Context context) {
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(context, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
Android Manifest
.
.
.
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.location.MODE_CHANGED" />
<action android:name="android.location.PROVIDERS_CHANGED" />
</intent-filter>
</receiver>
.
.

How to Use com.google.android.gms.common.api.GoogleApiClient, not the ActivityRecognitionClient, to request ActivityUpdates in android?

The motto here is calling the Service 'ActivityTrackerService' when I say requestActivityUpdates() using the GoogleApiClient's ActivityRecognition.ActivityRecognitionApi as shown in the code below when googleApiClient.connect() is called. After the api is connected the onConnected callback executes and activity updates are requested. The code runs perfectly fine as in the result call back i get a success. But some how Service class onHandleIntent is not called. I am not sure if the service has started working or not.
Service Provider Class:
public class ActivityServiceProvider {
private Context context;
private GoogleApiClient googleApiClient;
private PendingIntent mActivityRecognitionPendingIntent;
public ActivityServiceProvider(Context context) {
this.context = context;
createGoogleLocationServiceClient();
}
private void createGoogleLocationServiceClient() {
googleApiClient = new GoogleApiClient.Builder(context).addApi(ActivityRecognition.API)
.addConnectionCallbacks(new ConnectionCallbacks() {
#Override
public void onConnectionSuspended(int arg0) {
Log.d(ActivityUtils.APPTAG, "GoogleApiClient Suspended");
}
#Override
public void onConnected(Bundle arg0) {
Log.d(ActivityUtils.APPTAG, "GoogleApiClient Connected Now");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(googleApiClient,
ActivityUtils.DETECTION_INTERVAL_MILLISECONDS, getPendingIntent()).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status arg0) {
if (arg0.isSuccess()) {
Log.d(ActivityUtils.APPTAG, "Updates Requested Successfully");
} else {
Log.d(ActivityUtils.APPTAG, "Updates could not be requested");
}
}
});
}
}).addOnConnectionFailedListener(new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult arg0) {
Log.d(ActivityUtils.APPTAG, "GoogleApiClient Connection Failed");
}
}).build();
}
public PendingIntent getRequestPendingIntent() {
return mActivityRecognitionPendingIntent;
}
public void setRequestPendingIntent(PendingIntent intent) {
mActivityRecognitionPendingIntent = intent;
}
private PendingIntent getPendingIntent() {
Intent intent = new Intent(context, ActivityTrackerService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
setRequestPendingIntent(pendingIntent);
return pendingIntent;
}
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == resultCode) {
Log.d(ActivityUtils.APPTAG, context.getString(R.string.play_services_available));
return true;
} else {
Log.d(ActivityUtils.APPTAG, context.getString(R.string.play_services_unavailable));
return false;
}
}
public void connect() {
if (servicesConnected() && !googleApiClient.isConnected()) {
Log.d(ActivityUtils.APPTAG, "GoogleApiClient Connection Initiated: connect() Called");
googleApiClient.connect();
} else {
Log.d(ActivityUtils.APPTAG, "GoogleApiClient already connected or is unavailable");
}
}
public void disconnect() {
if (servicesConnected() && googleApiClient.isConnected()) {
Log.d(ActivityUtils.APPTAG, "GoogleApiClient disconnection kicked");
if (mActivityRecognitionPendingIntent != null && googleApiClient != null) {
ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(googleApiClient,
mActivityRecognitionPendingIntent);
}
googleApiClient.disconnect();
} else {
Log.d(ActivityUtils.APPTAG, "GoogleApiClient already disconnected or is unavailable");
}
}
}
Service Class:
public class ActivityTrackerService extends IntentService {
private SharedPreferences mPrefs;
public ActivityTrackerService() {
super("ActivityTrackerService");
}
#Override
protected void onHandleIntent(Intent intent) {
mPrefs = getApplicationContext().getSharedPreferences(ActivityUtils.SHARED_PREFERENCES, Context.MODE_PRIVATE);
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity mostProbableActivity = result.getMostProbableActivity();
int confidence = mostProbableActivity.getConfidence();
int activityType = mostProbableActivity.getType();
String activityName = ActivityUtils.getNameFromType(activityType);
Log.d(ActivityUtils.APPTAG, "Activity Detected:" + activityName);
Intent regularActivityUpdateIntent = new Intent(ActivityUtils.REGULAR_ACTIVITY_UPDATE_INTENT);
regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_NAME, activityName);
regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_TYPE, activityType);
getApplicationContext().sendBroadcast(regularActivityUpdateIntent);
if (!mPrefs.contains(ActivityUtils.KEY_PREVIOUS_ACTIVITY_TYPE)) {
Editor editor = mPrefs.edit();
editor.putInt(ActivityUtils.KEY_PREVIOUS_ACTIVITY_TYPE, activityType);
editor.putString(ActivityUtils.KEY_PREVIOUS_ACTIVITY_NAME, activityName);
editor.commit();
Intent newActivityUpdateIntent = new Intent(ActivityUtils.NEW_ACTIVITY_UPDATE_INTENT);
regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_NAME, activityName);
regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_TYPE, activityType);
getApplicationContext().sendBroadcast(newActivityUpdateIntent);
} else if (isMoving(activityType) && activityChanged(activityType) && (confidence >= 50)) {
sendNotification();
}
}
}
private void sendNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setContentTitle("Attention").setContentText("Click to turn on GPS, or swipe to ignore")
.setSmallIcon(R.drawable.ic_notification).setContentIntent(getContentIntent());
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifyManager.notify(0, builder.build());
}
private PendingIntent getContentIntent() {
Intent gpsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
return PendingIntent.getActivity(getApplicationContext(), 0, gpsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private boolean activityChanged(int currentType) {
int previousType = mPrefs.getInt(ActivityUtils.KEY_PREVIOUS_ACTIVITY_TYPE, DetectedActivity.UNKNOWN);
if (previousType != currentType) {
return true;
} else {
return false;
}
}
private boolean isMoving(int type) {
switch (type) {
case DetectedActivity.STILL:
case DetectedActivity.TILTING:
case DetectedActivity.UNKNOWN:
return false;
default:
return true;
}
}
}
The specific android manifest entries are as follows :
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<service android:name=".ActivityTrackerService" >
</service>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Has anybody tried using the com.google.android.gms.common.api.GoogleApiClient to request for ActivityUpdates using ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates or Is there some othe rway to use GoogleApiClient to request activity updates ??
I had the same problem, and even with explicit intent the onHandleIntent() would not be called.
I found that onStartCommand was called however, and could get around it by setting and checking the intent action.
It is not an explanation or solutions per se, but at least a workaound ;)
you should write your project's gradle (app)
dependencies{
compile 'com.google.firebase:firebase-appindexing:11.8.0'
....
}
then add libraries and import.

android Geofence won't get any Transition updates

Geofence does not get any transition updates, despite setting location 100 miles away,
does not trigger anything even GPS is on.
public class GeofenceManager extends IntentService implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationClient.OnAddGeofencesResultListener, LocationClient.OnRemoveGeofencesResultListener {
private Context context;
private LocationClient locClient;
private PendingIntent penIntent;
private ArrayList<Geofence> geofenceList = new ArrayList<Geofence>();
private double dLongitude, dLatitude;
private boolean bGeofenceEnable = false;
private BroadcastReceiver receiverGeofence;
/* ===========================================================================================================================
* CONSTRUCTOR -- Checks if Google play service are available
*----------------------------------------------------------------------------------------------------------------------------*/
GeofenceManager(Context context){
super("ReceiveTransitionsIntentService");
this.context = context;
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == resultCode) {
bGeofenceEnable = true;
} else {
Log.d(GPSManager.LOG_TAG,"GEO_FENCE: ERROR google play services not available");
}
}
/* ===========================================================================================================================
* METHOD -- using hard coded values for test purpose
*----------------------------------------------------------------------------------------------------------------------------*/
public void setGeofence( double latitude, double longitude){
if(bGeofenceEnable){
dLatitude = latitude = 51.515399;
dLongitude = longitude = -0.144313;
locClient.connect();
}
}
private PendingIntent createRequestPendingIntent() {
if (null != penIntent) {
return penIntent;
} else {
Intent intent = new Intent(context, GeofenceManager.class); // Create an Intent pointing to the IntentService
return PendingIntent.getService( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
#Override public void onConnected(Bundle bundle) {
Geofence geofence = new Geofence.Builder()
.setRequestId("123")
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT|Geofence.GEOFENCE_TRANSITION_ENTER ) // exit geo fence listener
.setCircularRegion(dLatitude, dLongitude, 20) // GPS coordinates
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
geofenceList.add(geofence);
penIntent = createRequestPendingIntent();
locClient.addGeofences(geofenceList, penIntent, this);
}
#Override public void onDisconnected() { }
#Override public void onConnectionFailed(ConnectionResult connectionResult) { }
#Override public void onRemoveGeofencesByPendingIntentResult(int i, PendingIntent pendingIntent) { }
#Override public void onAddGeofencesResult(int i, String[] strings) {
if(i == LocationStatusCodes.SUCCESS){
Log.d(GPSManager.LOG_TAG, GPSManager.getTime()+" GEO_FENCE: added");
} else {
Log.d(GPSManager.LOG_TAG, GPSManager.getTime()+" GEO_FENCE: add ERROR "+i);
}
// locClient.disconnect();
}
#Override public void onRemoveGeofencesByRequestIdsResult(int i, String[] strings) {
if(i == LocationStatusCodes.SUCCESS)
Log.d(GPSManager.LOG_TAG, GPSManager.getTime()+" GEO_FENCE: old Removed");
}
#Override protected void onHandleIntent(Intent intent) {
int transition = LocationClient.getGeofenceTransition(intent);
if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER) || (transition == Geofence.GEOFENCE_TRANSITION_EXIT)){
Log.d(GPSManager.LOG_TAG,"GEO_FENCE Transition detected");
Toast.makeText(context, "Geo fence movement detected", Toast.LENGTH_LONG).show();
ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 1000); // 200 is duration in ms
} else {
Log.d(GPSManager.LOG_TAG,"GEO_FENCE Transition UPDATE");
}
}
}
and in Manifest file I have declared:
<service android:name="com.Utilities.GeofenceManager" android:exported="true" />
also have tried:
<service android:name="com.Utilities.GeofenceManager" android:exported="false" />
<service android:name=".GeofenceManager" android:exported="false" />
Geofence is added as onAddGeofencesResult() method is called with success
Manage to fix the problem, by creating a new class for Geofence transition Intent,
and removed the IntentService code from GeofenceManager class
public class GeofenceIntentService extends IntentService {
public GeofenceIntentService() {
super("GeofenceIntentService");
}
#Override protected void onHandleIntent(Intent intent) {
int transition = LocationClient.getGeofenceTransition(intent);
if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER) || (transition == Geofence.GEOFENCE_TRANSITION_EXIT)){
Log.d(GPSManager.LOG_TAG, "GEO_FENCE "+((transition == Geofence.GEOFENCE_TRANSITION_ENTER) ? "ENTER " : "EXIT") +" Transition detected");
Toast.makeText(this, "Geo fence movement detected", Toast.LENGTH_LONG).show();
ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, 80);
toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE, 1000); // 200 is duration in ms
} else {
Log.d(GPSManager.LOG_TAG,"GEO_FENCE Transition UPDATE");
}
}
}

Categories

Resources